actual freya branch

This commit is contained in:
2026-09-12 15:41:31 +00:00
parent 8049e0a882
commit 68c1cd27d4
3510 changed files with 336689 additions and 302906 deletions
@@ -0,0 +1,82 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
/**
* @author mrTJO
*/
public class ActionKey
{
int _cat;
int _cmd;
int _key;
int _tgKey1;
int _tgKey2;
int _show;
/**
* L2ActionKey Initialization
* @param cat: Category ID
* @param cmd: Command ID
* @param key: User Defined Primary Key
* @param tgKey1: 1st Toogled Key (eg. Alt, Ctrl or Shift)
* @param tgKey2: 2nd Toogled Key (eg. Alt, Ctrl or Shift)
* @param show: Show Action in UI
*/
public ActionKey(int cat, int cmd, int key, int tgKey1, int tgKey2, int show)
{
_cat = cat;
_cmd = cmd;
_key = key;
_tgKey1 = tgKey1;
_tgKey2 = tgKey2;
_show = show;
}
public int getCategory()
{
return _cat;
}
public int getCommandId()
{
return _cmd;
}
public int getKeyId()
{
return _key;
}
public int getToogleKey1()
{
return _tgKey1;
}
public int getToogleKey2()
{
return _tgKey2;
}
public int getShowStatus()
{
return _show;
}
public String getSqlSaveString(int playerId, int order)
{
return "(" + playerId + ", " + _cat + ", " + order + ", " + _cmd + "," + _key + ", " + _tgKey1 + ", " + _tgKey2 + ", " + _show + ")";
}
}
@@ -0,0 +1,660 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import static com.l2jserver.gameserver.model.itemcontainer.PcInventory.ADENA_ID;
import static com.l2jserver.gameserver.model.itemcontainer.PcInventory.MAX_ADENA;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javolution.util.FastMap;
import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.datatables.ClanTable;
import com.l2jserver.gameserver.idfactory.IdFactory;
import com.l2jserver.gameserver.instancemanager.AuctionManager;
import com.l2jserver.gameserver.instancemanager.ClanHallManager;
import com.l2jserver.gameserver.model.L2Clan;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
public class Auction
{
protected static final Logger _log = Logger.getLogger(Auction.class.getName());
private int _id = 0;
private long _endDate;
private int _highestBidderId = 0;
private String _highestBidderName = "";
private long _highestBidderMaxBid = 0;
private int _itemId = 0;
private String _itemName = "";
private int _itemObjectId = 0;
private final long _itemQuantity = 0;
private String _itemType = "";
private int _sellerId = 0;
private String _sellerClanName = "";
private String _sellerName = "";
private long _currentBid = 0;
private long _startingBid = 0;
private final Map<Integer, Bidder> _bidders = new FastMap<>();
private static final String[] ItemTypeName =
{
"ClanHall"
};
public static enum ItemTypeEnum
{
ClanHall
}
public static class Bidder
{
private final String _name; // TODO replace with objid
private final String _clanName;
private long _bid;
private final Calendar _timeBid;
public Bidder(String name, String clanName, long bid, long timeBid)
{
_name = name;
_clanName = clanName;
_bid = bid;
_timeBid = Calendar.getInstance();
_timeBid.setTimeInMillis(timeBid);
}
public String getName()
{
return _name;
}
public String getClanName()
{
return _clanName;
}
public long getBid()
{
return _bid;
}
public Calendar getTimeBid()
{
return _timeBid;
}
public void setTimeBid(long timeBid)
{
_timeBid.setTimeInMillis(timeBid);
}
public void setBid(long bid)
{
_bid = bid;
}
}
/** Task Sheduler for endAuction */
public class AutoEndTask implements Runnable
{
public AutoEndTask()
{
}
@Override
public void run()
{
try
{
endAuction();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "", e);
}
}
}
/** Constructor */
public Auction(int auctionId)
{
_id = auctionId;
load();
startAutoTask();
}
public Auction(int itemId, L2Clan Clan, long delay, long bid, String name)
{
_id = itemId;
_endDate = System.currentTimeMillis() + delay;
_itemId = itemId;
_itemName = name;
_itemType = "ClanHall";
_sellerId = Clan.getLeaderId();
_sellerName = Clan.getLeaderName();
_sellerClanName = Clan.getName();
_startingBid = bid;
}
/** Load auctions */
private void load()
{
Connection con = null;
try
{
PreparedStatement statement;
ResultSet rs;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("Select * from auction where id = ?");
statement.setInt(1, getId());
rs = statement.executeQuery();
while (rs.next())
{
_currentBid = rs.getLong("currentBid");
_endDate = rs.getLong("endDate");
_itemId = rs.getInt("itemId");
_itemName = rs.getString("itemName");
_itemObjectId = rs.getInt("itemObjectId");
_itemType = rs.getString("itemType");
_sellerId = rs.getInt("sellerId");
_sellerClanName = rs.getString("sellerClanName");
_sellerName = rs.getString("sellerName");
_startingBid = rs.getLong("startingBid");
}
statement.close();
loadBid();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: Auction.load(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Load bidders **/
private void loadBid()
{
_highestBidderId = 0;
_highestBidderName = "";
_highestBidderMaxBid = 0;
Connection con = null;
try
{
PreparedStatement statement;
ResultSet rs;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("SELECT bidderId, bidderName, maxBid, clan_name, time_bid FROM auction_bid WHERE auctionId = ? ORDER BY maxBid DESC");
statement.setInt(1, getId());
rs = statement.executeQuery();
while (rs.next())
{
if (rs.isFirst())
{
_highestBidderId = rs.getInt("bidderId");
_highestBidderName = rs.getString("bidderName");
_highestBidderMaxBid = rs.getLong("maxBid");
}
_bidders.put(rs.getInt("bidderId"), new Bidder(rs.getString("bidderName"), rs.getString("clan_name"), rs.getLong("maxBid"), rs.getLong("time_bid")));
}
statement.close();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: Auction.loadBid(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Task Manage */
private void startAutoTask()
{
long currentTime = System.currentTimeMillis();
long taskDelay = 0;
if (_endDate <= currentTime)
{
_endDate = currentTime + (7 * 24 * 60 * 60 * 1000);
saveAuctionDate();
}
else
{
taskDelay = _endDate - currentTime;
}
ThreadPoolManager.getInstance().scheduleGeneral(new AutoEndTask(), taskDelay);
}
public static String getItemTypeName(ItemTypeEnum value)
{
return ItemTypeName[value.ordinal()];
}
/** Save Auction Data End */
private void saveAuctionDate()
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement("Update auction set endDate = ? where id = ?");
statement.setLong(1, _endDate);
statement.setInt(2, _id);
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: saveAuctionDate(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Set a bid */
public synchronized void setBid(L2PcInstance bidder, long bid)
{
long requiredAdena = bid;
if (getHighestBidderName().equals(bidder.getClan().getLeaderName()))
{
requiredAdena = bid - getHighestBidderMaxBid();
}
if (((getHighestBidderId() > 0) && (bid > getHighestBidderMaxBid())) || ((getHighestBidderId() == 0) && (bid >= getStartingBid())))
{
if (takeItem(bidder, requiredAdena))
{
updateInDB(bidder, bid);
bidder.getClan().setAuctionBiddedAt(_id, true);
return;
}
}
if ((bid < getStartingBid()) || (bid <= getHighestBidderMaxBid()))
{
bidder.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.BID_PRICE_MUST_BE_HIGHER));
}
}
/** Return Item in WHC */
private void returnItem(String Clan, long quantity, boolean penalty)
{
if (penalty)
{
quantity *= 0.9; // take 10% tax fee if needed
}
// avoid overflow on return
final long limit = MAX_ADENA - ClanTable.getInstance().getClanByName(Clan).getWarehouse().getAdena();
quantity = Math.min(quantity, limit);
ClanTable.getInstance().getClanByName(Clan).getWarehouse().addItem("Outbidded", ADENA_ID, quantity, null, null);
}
/** Take Item in WHC */
private boolean takeItem(L2PcInstance bidder, long quantity)
{
if ((bidder.getClan() != null) && (bidder.getClan().getWarehouse().getAdena() >= quantity))
{
bidder.getClan().getWarehouse().destroyItemByItemId("Buy", ADENA_ID, quantity, bidder, bidder);
return true;
}
bidder.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.NOT_ENOUGH_ADENA_IN_CWH));
return false;
}
/** Update auction in DB */
private void updateInDB(L2PcInstance bidder, long bid)
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
if (getBidders().get(bidder.getClanId()) != null)
{
statement = con.prepareStatement("UPDATE auction_bid SET bidderId=?, bidderName=?, maxBid=?, time_bid=? WHERE auctionId=? AND bidderId=?");
statement.setInt(1, bidder.getClanId());
statement.setString(2, bidder.getClan().getLeaderName());
statement.setLong(3, bid);
statement.setLong(4, System.currentTimeMillis());
statement.setInt(5, getId());
statement.setInt(6, bidder.getClanId());
statement.execute();
statement.close();
}
else
{
statement = con.prepareStatement("INSERT INTO auction_bid (id, auctionId, bidderId, bidderName, maxBid, clan_name, time_bid) VALUES (?, ?, ?, ?, ?, ?, ?)");
statement.setInt(1, IdFactory.getInstance().getNextId());
statement.setInt(2, getId());
statement.setInt(3, bidder.getClanId());
statement.setString(4, bidder.getName());
statement.setLong(5, bid);
statement.setString(6, bidder.getClan().getName());
statement.setLong(7, System.currentTimeMillis());
statement.execute();
statement.close();
if (L2World.getInstance().getPlayer(_highestBidderName) != null)
{
L2World.getInstance().getPlayer(_highestBidderName).sendMessage("You have been out bidded");
}
}
_highestBidderId = bidder.getClanId();
_highestBidderMaxBid = bid;
_highestBidderName = bidder.getClan().getLeaderName();
if (_bidders.get(_highestBidderId) == null)
{
_bidders.put(_highestBidderId, new Bidder(_highestBidderName, bidder.getClan().getName(), bid, Calendar.getInstance().getTimeInMillis()));
}
else
{
_bidders.get(_highestBidderId).setBid(bid);
_bidders.get(_highestBidderId).setTimeBid(Calendar.getInstance().getTimeInMillis());
}
bidder.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.BID_IN_CLANHALL_AUCTION));
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Auction.updateInDB(L2PcInstance bidder, int bid): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Remove bids */
private void removeBids()
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=?");
statement.setInt(1, getId());
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Auction.deleteFromDB(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
for (Bidder b : _bidders.values())
{
if (ClanTable.getInstance().getClanByName(b.getClanName()).getHasHideout() == 0)
{
returnItem(b.getClanName(), b.getBid(), true); // 10 % tax
}
else
{
if (L2World.getInstance().getPlayer(b.getName()) != null)
{
L2World.getInstance().getPlayer(b.getName()).sendMessage("Congratulation you have won ClanHall!");
}
}
ClanTable.getInstance().getClanByName(b.getClanName()).setAuctionBiddedAt(0, true);
}
_bidders.clear();
}
/** Remove auctions */
public void deleteAuctionFromDB()
{
AuctionManager.getInstance().getAuctions().remove(this);
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM auction WHERE itemId=?");
statement.setInt(1, _itemId);
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Auction.deleteFromDB(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** End of auction */
public void endAuction()
{
if (ClanHallManager.getInstance().loaded())
{
if ((_highestBidderId == 0) && (_sellerId == 0))
{
startAutoTask();
return;
}
if ((_highestBidderId == 0) && (_sellerId > 0))
{
/**
* If seller haven't sell ClanHall, auction removed, THIS MUST BE CONFIRMED
*/
int aucId = AuctionManager.getInstance().getAuctionIndex(_id);
AuctionManager.getInstance().getAuctions().remove(aucId);
return;
}
if (_sellerId > 0)
{
returnItem(_sellerClanName, _highestBidderMaxBid, true);
returnItem(_sellerClanName, ClanHallManager.getInstance().getClanHallById(_itemId).getLease(), false);
}
deleteAuctionFromDB();
L2Clan Clan = ClanTable.getInstance().getClanByName(_bidders.get(_highestBidderId).getClanName());
_bidders.remove(_highestBidderId);
Clan.setAuctionBiddedAt(0, true);
removeBids();
ClanHallManager.getInstance().setOwner(_itemId, Clan);
}
else
{
/** Task waiting ClanHallManager is loaded every 3s */
ThreadPoolManager.getInstance().scheduleGeneral(new AutoEndTask(), 3000);
}
}
/** Cancel bid */
public synchronized void cancelBid(int bidder)
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM auction_bid WHERE auctionId=? AND bidderId=?");
statement.setInt(1, getId());
statement.setInt(2, bidder);
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Auction.cancelBid(String bidder): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
returnItem(_bidders.get(bidder).getClanName(), _bidders.get(bidder).getBid(), true);
ClanTable.getInstance().getClanByName(_bidders.get(bidder).getClanName()).setAuctionBiddedAt(0, true);
_bidders.clear();
loadBid();
}
/** Cancel auction */
public void cancelAuction()
{
deleteAuctionFromDB();
removeBids();
}
/** Confirm an auction */
public void confirmAuction()
{
AuctionManager.getInstance().getAuctions().add(this);
Connection con = null;
try
{
PreparedStatement statement;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("INSERT INTO auction (id, sellerId, sellerName, sellerClanName, itemType, itemId, itemObjectId, itemName, itemQuantity, startingBid, currentBid, endDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
statement.setInt(1, getId());
statement.setInt(2, _sellerId);
statement.setString(3, _sellerName);
statement.setString(4, _sellerClanName);
statement.setString(5, _itemType);
statement.setInt(6, _itemId);
statement.setInt(7, _itemObjectId);
statement.setString(8, _itemName);
statement.setLong(9, _itemQuantity);
statement.setLong(10, _startingBid);
statement.setLong(11, _currentBid);
statement.setLong(12, _endDate);
statement.execute();
statement.close();
loadBid();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Auction.load(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Get var auction */
public final int getId()
{
return _id;
}
public final long getCurrentBid()
{
return _currentBid;
}
public final long getEndDate()
{
return _endDate;
}
public final int getHighestBidderId()
{
return _highestBidderId;
}
public final String getHighestBidderName()
{
return _highestBidderName;
}
public final long getHighestBidderMaxBid()
{
return _highestBidderMaxBid;
}
public final int getItemId()
{
return _itemId;
}
public final String getItemName()
{
return _itemName;
}
public final int getItemObjectId()
{
return _itemObjectId;
}
public final long getItemQuantity()
{
return _itemQuantity;
}
public final String getItemType()
{
return _itemType;
}
public final int getSellerId()
{
return _sellerId;
}
public final String getSellerName()
{
return _sellerName;
}
public final String getSellerClanName()
{
return _sellerClanName;
}
public final long getStartingBid()
{
return _startingBid;
}
public final Map<Integer, Bidder> getBidders()
{
return _bidders;
}
}
@@ -0,0 +1,785 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import javolution.util.FastList;
import javolution.util.FastMap;
import com.l2jserver.Config;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.datatables.NpcTable;
import com.l2jserver.gameserver.datatables.SkillTable;
import com.l2jserver.gameserver.datatables.SpawnTable;
import com.l2jserver.gameserver.instancemanager.HandysBlockCheckerManager;
import com.l2jserver.gameserver.instancemanager.HandysBlockCheckerManager.ArenaParticipantsHolder;
import com.l2jserver.gameserver.model.L2ItemInstance;
import com.l2jserver.gameserver.model.L2Skill;
import com.l2jserver.gameserver.model.L2Spawn;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.actor.instance.L2BlockInstance;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
import com.l2jserver.gameserver.network.serverpackets.ExBasicActionList;
import com.l2jserver.gameserver.network.serverpackets.ExCubeGameChangePoints;
import com.l2jserver.gameserver.network.serverpackets.ExCubeGameCloseUI;
import com.l2jserver.gameserver.network.serverpackets.ExCubeGameEnd;
import com.l2jserver.gameserver.network.serverpackets.ExCubeGameExtendedChangePoints;
import com.l2jserver.gameserver.network.serverpackets.RelationChanged;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.templates.chars.L2NpcTemplate;
import com.l2jserver.util.Rnd;
/**
* @author BiggBoss
*/
public final class BlockCheckerEngine
{
protected static final Logger _log = Logger.getLogger(BlockCheckerEngine.class.getName());
// The object which holds all basic members info
protected HandysBlockCheckerManager.ArenaParticipantsHolder _holder;
// Maps to hold player of each team and his points
protected final FastMap<L2PcInstance, Integer> _redTeamPoints = new FastMap<>();
protected final FastMap<L2PcInstance, Integer> _blueTeamPoints = new FastMap<>();
// The initial points of the event
protected int _redPoints = 15;
protected int _bluePoints = 15;
// Current used arena
protected int _arena = -1;
// All blocks
protected final FastList<L2Spawn> _spawns = new FastList<>();
// Sets if the red team won the event at the end of this (used for packets)
protected boolean _isRedWinner;
// Time when the event starts. Used on packet sending
protected long _startedTime;
// The needed arena coordinates
// Arena X: team1X, team1Y, team2X, team2Y, ArenaCenterX, ArenaCenterY
protected static final int[][] _arenaCoordinates =
{
// Arena 0 - Team 1 XY, Team 2 XY - CENTER XY
{
-58368,
-62745,
-57751,
-62131,
-58053,
-62417
},
// Arena 1 - Team 1 XY, Team 2 XY - CENTER XY
{
-58350,
-63853,
-57756,
-63266,
-58053,
-63551
},
// Arena 2 - Team 1 XY, Team 2 XY - CENTER XY
{
-57194,
-63861,
-56580,
-63249,
-56886,
-63551
},
// Arena 3 - Team 1 XY, Team 2 XY - CENTER XY
{
-57200,
-62727,
-56584,
-62115,
-56850,
-62391
}
};
// Common z coordinate
private static final int _zCoord = -2405;
// List of dropped items in event (for later deletion)
protected final FastList<L2ItemInstance> _drops = new FastList<>();
// Default arena
private static final byte DEFAULT_ARENA = -1;
// Event is started
protected boolean _isStarted = false;
// Event end
protected ScheduledFuture<?> _task;
// Preserve from exploit reward by logging out
protected boolean _abnormalEnd = false;
public BlockCheckerEngine(HandysBlockCheckerManager.ArenaParticipantsHolder holder, int arena)
{
_holder = holder;
if ((arena > -1) && (arena < 4))
{
_arena = arena;
}
for (L2PcInstance player : holder.getRedPlayers())
{
_redTeamPoints.put(player, 0);
}
for (L2PcInstance player : holder.getBluePlayers())
{
_blueTeamPoints.put(player, 0);
}
}
/**
* Updates the player holder before the event starts to synchronize all info
* @param holder
*/
public void updatePlayersOnStart(ArenaParticipantsHolder holder)
{
_holder = holder;
}
/**
* Returns the current holder object of this object engine
* @return HandysBlockCheckerManager.ArenaParticipantsHolder
*/
public ArenaParticipantsHolder getHolder()
{
return _holder;
}
/**
* Will return the id of the arena used by this event
* @return false;
*/
public int getArena()
{
return _arena;
}
/**
* Returns the time when the event started
* @return long
*/
public long getStarterTime()
{
return _startedTime;
}
/**
* Returns the current red team points
* @return int
*/
public int getRedPoints()
{
synchronized (this)
{
return _redPoints;
}
}
/**
* Returns the current blue team points
* @return int
*/
public int getBluePoints()
{
synchronized (this)
{
return _bluePoints;
}
}
/**
* Returns the player points
* @param player
* @param isRed
* @return int
*/
public int getPlayerPoints(L2PcInstance player, boolean isRed)
{
if (!_redTeamPoints.containsKey(player) && !_blueTeamPoints.containsKey(player))
{
return 0;
}
if (isRed)
{
return _redTeamPoints.get(player);
}
return _blueTeamPoints.get(player);
}
/**
* Increases player points for his teams
* @param player
* @param team
*/
public synchronized void increasePlayerPoints(L2PcInstance player, int team)
{
if (player == null)
{
return;
}
if (team == 0)
{
int points = _redTeamPoints.get(player) + 1;
_redTeamPoints.put(player, points);
_redPoints++;
_bluePoints--;
}
else
{
int points = _blueTeamPoints.get(player) + 1;
_blueTeamPoints.put(player, points);
_bluePoints++;
_redPoints--;
}
}
/**
* Will add a new drop into the list of dropped items
* @param item
*/
public void addNewDrop(L2ItemInstance item)
{
if (item != null)
{
_drops.add(item);
}
}
/**
* Will return true if the event is alredy started
* @return boolean
*/
public boolean isStarted()
{
return _isStarted;
}
/**
* Will send all packets for the event members with the relation info
*/
protected void broadcastRelationChanged(L2PcInstance plr)
{
for (L2PcInstance p : _holder.getAllPlayers())
{
p.sendPacket(new RelationChanged(plr, plr.getRelation(p), plr.isAutoAttackable(p)));
}
}
/**
* Called when a there is an empty team. The event will end.
*/
public void endEventAbnormally()
{
try
{
synchronized (this)
{
_isStarted = false;
if (_task != null)
{
_task.cancel(true);
}
_abnormalEnd = true;
ThreadPoolManager.getInstance().executeTask(new EndEvent());
if (Config.DEBUG)
{
_log.config("Handys Block Checker Event at arena " + _arena + " ended due lack of players!");
}
}
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Couldnt end Block Checker event at " + _arena, e);
}
}
/**
* This inner class set ups all player and arena parameters to start the event
*/
public class StartEvent implements Runnable
{
// In event used skills
private final L2Skill _freeze, _transformationRed, _transformationBlue;
// Common and unparametizer packet
private final ExCubeGameCloseUI _closeUserInterface = new ExCubeGameCloseUI();
public StartEvent()
{
// Initialize all used skills
_freeze = SkillTable.getInstance().getInfo(6034, 1);
_transformationRed = SkillTable.getInstance().getInfo(6035, 1);
_transformationBlue = SkillTable.getInstance().getInfo(6036, 1);
}
/**
* Will set up all player parameters and port them to their respective location based on their teams
*/
private void setUpPlayers()
{
// Set current arena as being used
HandysBlockCheckerManager.getInstance().setArenaBeingUsed(_arena);
// Initialize packets avoiding create a new one per player
_redPoints = _spawns.size() / 2;
_bluePoints = _spawns.size() / 2;
final ExCubeGameChangePoints initialPoints = new ExCubeGameChangePoints(300, _bluePoints, _redPoints);
ExCubeGameExtendedChangePoints clientSetUp;
for (L2PcInstance player : _holder.getAllPlayers())
{
if (player == null)
{
continue;
}
// Send the secret client packet set up
boolean isRed = _holder.getRedPlayers().contains(player);
clientSetUp = new ExCubeGameExtendedChangePoints(300, _bluePoints, _redPoints, isRed, player, 0);
player.sendPacket(clientSetUp);
player.sendPacket(ActionFailed.STATIC_PACKET);
// Teleport Player - Array access
// Team 0 * 2 = 0; 0 = 0, 0 + 1 = 1.
// Team 1 * 2 = 2; 2 = 2, 2 + 1 = 3
int tc = _holder.getPlayerTeam(player) * 2;
// Get x and y coordinates
int x = _arenaCoordinates[_arena][tc];
int y = _arenaCoordinates[_arena][tc + 1];
player.teleToLocation(x, y, _zCoord);
// Set the player team
if (isRed)
{
_redTeamPoints.put(player, 0);
player.setTeam(2);
}
else
{
_blueTeamPoints.put(player, 0);
player.setTeam(1);
}
player.stopAllEffects();
if (player.getPet() != null)
{
player.getPet().unSummon(player);
}
// Give the player start up effects
// Freeze
_freeze.getEffects(player, player);
// Tranformation
if (_holder.getPlayerTeam(player) == 0)
{
_transformationRed.getEffects(player, player);
}
else
{
_transformationBlue.getEffects(player, player);
}
// Set the current player arena
player.setBlockCheckerArena((byte) _arena);
player.setInsideZone(L2Character.ZONE_PVP, true);
// Send needed packets
player.sendPacket(initialPoints);
player.sendPacket(_closeUserInterface);
// ExBasicActionList
final ExBasicActionList actionList = ExBasicActionList.getStaticPacket(player);
player.sendPacket(actionList);
broadcastRelationChanged(player);
}
}
@Override
public void run()
{
// Wrong arena passed, stop event
if (_arena == -1)
{
_log.severe("Couldnt set up the arena Id for the Block Checker event, cancelling event...");
return;
}
_isStarted = true;
// Spawn the blocks
ThreadPoolManager.getInstance().executeTask(new SpawnRound(16, 1));
// Start up player parameters
setUpPlayers();
// Set the started time
_startedTime = System.currentTimeMillis() + 300000;
}
}
/**
* This class spawns the second round of boxes and schedules the event end
*/
private class SpawnRound implements Runnable
{
int _numOfBoxes;
int _round;
SpawnRound(int numberOfBoxes, int round)
{
_numOfBoxes = numberOfBoxes;
_round = round;
}
@Override
public void run()
{
if (!_isStarted)
{
return;
}
switch (_round)
{
case 1:
// Schedule second spawn round
_task = ThreadPoolManager.getInstance().scheduleGeneral(new SpawnRound(20, 2), 60000);
break;
case 2:
// Schedule third spawn round
_task = ThreadPoolManager.getInstance().scheduleGeneral(new SpawnRound(14, 3), 60000);
break;
case 3:
// Schedule Event End Count Down
_task = ThreadPoolManager.getInstance().scheduleGeneral(new EndEvent(), 180000);
break;
}
// random % 2, if == 0 will spawn a red block
// if != 0, will spawn a blue block
byte random = 2;
// common template
final L2NpcTemplate template = NpcTable.getInstance().getTemplate(18672);
// Spawn blocks
try
{
// Creates 50 new blocks
for (int i = 0; i < _numOfBoxes; i++)
{
L2Spawn spawn = new L2Spawn(template);
spawn.setLocx(_arenaCoordinates[_arena][4] + Rnd.get(-400, 400));
spawn.setLocy(_arenaCoordinates[_arena][5] + Rnd.get(-400, 400));
spawn.setLocz(_zCoord);
spawn.setAmount(1);
spawn.setHeading(1);
spawn.setRespawnDelay(1);
SpawnTable.getInstance().addNewSpawn(spawn, false);
spawn.init();
L2BlockInstance block = (L2BlockInstance) spawn.getLastSpawn();
// switch color
if ((random % 2) == 0)
{
block.setRed(true);
}
else
{
block.setRed(false);
}
block.disableCoreAI(true);
_spawns.add(spawn);
random++;
}
}
catch (Exception e)
{
e.printStackTrace();
}
// Spawn the block carrying girl
if ((_round == 1) || (_round == 2))
{
L2NpcTemplate girl = NpcTable.getInstance().getTemplate(18676);
try
{
final L2Spawn girlSpawn = new L2Spawn(girl);
girlSpawn.setLocx(_arenaCoordinates[_arena][4] + Rnd.get(-400, 400));
girlSpawn.setLocy(_arenaCoordinates[_arena][5] + Rnd.get(-400, 400));
girlSpawn.setLocz(_zCoord);
girlSpawn.setAmount(1);
girlSpawn.setHeading(1);
girlSpawn.setRespawnDelay(1);
SpawnTable.getInstance().addNewSpawn(girlSpawn, false);
girlSpawn.init();
// Schedule his deletion after 9 secs of spawn
ThreadPoolManager.getInstance().scheduleGeneral(new CarryingGirlUnspawn(girlSpawn), 9000);
}
catch (Exception e)
{
_log.warning("Couldnt Spawn Block Checker NPCs! Wrong instance type at npc table?");
if (Config.DEBUG)
{
e.printStackTrace();
}
}
}
_redPoints += _numOfBoxes / 2;
_bluePoints += _numOfBoxes / 2;
int timeLeft = (int) ((getStarterTime() - System.currentTimeMillis()) / 1000);
ExCubeGameChangePoints changePoints = new ExCubeGameChangePoints(timeLeft, getBluePoints(), getRedPoints());
getHolder().broadCastPacketToTeam(changePoints);
}
}
private class CarryingGirlUnspawn implements Runnable
{
private final L2Spawn _spawn;
protected CarryingGirlUnspawn(L2Spawn spawn)
{
_spawn = spawn;
}
@Override
public void run()
{
if (_spawn == null)
{
_log.warning("HBCE: Block Carrying Girl is null");
return;
}
SpawnTable.getInstance().deleteSpawn(_spawn, false);
_spawn.stopRespawn();
_spawn.getLastSpawn().deleteMe();
}
}
/*
* private class CountDown implements Runnable {
* @Override public void run() { _holder.broadCastPacketToTeam(SystemMessage.getSystemMessage(SystemMessageId.BLOCK_CHECKER_ENDS_5)); ThreadPoolManager.getInstance().scheduleGeneral(new EndEvent(), 5000); } }
*/
/**
* This class erase all event parameters on player and port them back near Handy. Also, unspawn blocks, runs a garbage collector and set as free the used arena
*/
protected class EndEvent implements Runnable
{
// Garbage collector and arena free setter
private void clearMe()
{
HandysBlockCheckerManager.getInstance().clearPaticipantQueueByArenaId(_arena);
_holder.clearPlayers();
_blueTeamPoints.clear();
_redTeamPoints.clear();
HandysBlockCheckerManager.getInstance().setArenaFree(_arena);
for (L2Spawn spawn : _spawns)
{
spawn.stopRespawn();
spawn.getLastSpawn().deleteMe();
SpawnTable.getInstance().deleteSpawn(spawn, false);
spawn = null;
}
_spawns.clear();
for (L2ItemInstance item : _drops)
{
// npe
if (item == null)
{
continue;
}
// a player has it, it will be deleted later
if (!item.isVisible() || (item.getOwnerId() != 0))
{
continue;
}
item.decayMe();
L2World.getInstance().removeObject(item);
}
_drops.clear();
}
/**
* Reward players after event. Tie - No Reward
*/
private void rewardPlayers()
{
if (_redPoints == _bluePoints)
{
return;
}
_isRedWinner = _redPoints > _bluePoints ? true : false;
if (_isRedWinner)
{
rewardAsWinner(true);
rewardAsLooser(false);
SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.TEAM_C1_WON);
msg.addString("Red Team");
_holder.broadCastPacketToTeam(msg);
}
else if (_bluePoints > _redPoints)
{
rewardAsWinner(false);
rewardAsLooser(true);
SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.TEAM_C1_WON);
msg.addString("Blue Team");
_holder.broadCastPacketToTeam(msg);
}
else
{
rewardAsLooser(true);
rewardAsLooser(false);
}
}
/**
* Reward the speicifed team as a winner team 1) Higher score - 8 extra 2) Higher score - 5 extra
* @param isRed
*/
private void rewardAsWinner(boolean isRed)
{
FastMap<L2PcInstance, Integer> tempPoints = isRed ? _redTeamPoints : _blueTeamPoints;
// Main give
for (L2PcInstance pc : tempPoints.keySet())
{
if (pc == null)
{
continue;
}
if (tempPoints.get(pc) >= 10)
{
pc.addItem("Block Checker", 13067, 2, pc, true);
}
else
{
tempPoints.remove(pc);
}
}
int first = 0, second = 0;
L2PcInstance winner1 = null, winner2 = null;
for (Entry<L2PcInstance, Integer> entry : tempPoints.entrySet())
{
L2PcInstance pc = entry.getKey();
int pcPoints = entry.getValue();
if (pcPoints > first)
{
// Move old data
second = first;
winner2 = winner1;
// Set new data
first = pcPoints;
winner1 = pc;
}
else if (pcPoints > second)
{
second = pcPoints;
winner2 = pc;
}
}
if (winner1 != null)
{
winner1.addItem("Block Checker", 13067, 8, winner1, true);
}
if (winner2 != null)
{
winner2.addItem("Block Checker", 13067, 5, winner2, true);
}
}
/**
* Will reward the looser team with the predefined rewards Player got >= 10 points: 2 coins Player got < 10 points: 0 coins
* @param isRed
*/
private void rewardAsLooser(boolean isRed)
{
FastMap<L2PcInstance, Integer> tempPoints = isRed ? _redTeamPoints : _blueTeamPoints;
for (Entry<L2PcInstance, Integer> entry : tempPoints.entrySet())
{
L2PcInstance player = entry.getKey();
if ((player != null) && (entry.getValue() >= 10))
{
player.addItem("Block Checker", 13067, 2, player, true);
}
}
}
/**
* Telport players back, give status back and send final packet
*/
private void setPlayersBack()
{
final ExCubeGameEnd end = new ExCubeGameEnd(_isRedWinner);
for (L2PcInstance player : _holder.getAllPlayers())
{
if (player == null)
{
continue;
}
player.stopAllEffects();
// Remove team aura
player.setTeam(0);
// Set default arena
player.setBlockCheckerArena(DEFAULT_ARENA);
// Remove the event items
PcInventory inv = player.getInventory();
if (inv.getItemByItemId(13787) != null)
{
long count = inv.getInventoryItemCount(13787, 0);
inv.destroyItemByItemId("Handys Block Checker", 13787, count, player, player);
}
if (inv.getItemByItemId(13788) != null)
{
long count = inv.getInventoryItemCount(13788, 0);
inv.destroyItemByItemId("Handys Block Checker", 13788, count, player, player);
}
broadcastRelationChanged(player);
// Teleport Back
player.teleToLocation(-57478, -60367, -2370);
player.setInsideZone(L2Character.ZONE_PVP, false);
// Send end packet
player.sendPacket(end);
player.broadcastUserInfo();
}
}
@Override
public void run()
{
if (!_abnormalEnd)
{
rewardPlayers();
}
setPlayersBack();
clearMe();
_isStarted = false;
_abnormalEnd = false;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,728 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javolution.util.FastList;
import javolution.util.FastMap;
import com.l2jserver.Config;
import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.datatables.ClanTable;
import com.l2jserver.gameserver.datatables.DoorTable;
import com.l2jserver.gameserver.instancemanager.AuctionManager;
import com.l2jserver.gameserver.instancemanager.ClanHallManager;
import com.l2jserver.gameserver.model.L2Clan;
import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.zone.type.L2ClanHallZone;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.PledgeShowInfoUpdate;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
public class ClanHall
{
protected static final Logger _log = Logger.getLogger(ClanHall.class.getName());
private final int _clanHallId;
private List<L2DoorInstance> _doors;
private final List<String> _doorDefault;
private final String _name;
private int _ownerId;
private final int _lease;
private final String _desc;
private final String _location;
protected long _paidUntil;
private L2ClanHallZone _zone;
private final int _grade;
protected final int _chRate = 604800000;
protected boolean _isFree = true;
private final Map<Integer, ClanHallFunction> _functions;
protected boolean _paid;
/** Clan Hall Functions */
public static final int FUNC_TELEPORT = 1;
public static final int FUNC_ITEM_CREATE = 2;
public static final int FUNC_RESTORE_HP = 3;
public static final int FUNC_RESTORE_MP = 4;
public static final int FUNC_RESTORE_EXP = 5;
public static final int FUNC_SUPPORT = 6;
public static final int FUNC_DECO_FRONTPLATEFORM = 7;
public static final int FUNC_DECO_CURTAINS = 8;
public class ClanHallFunction
{
private final int _type;
private int _lvl;
protected int _fee;
protected int _tempFee;
private final long _rate;
private long _endDate;
protected boolean _inDebt;
public boolean _cwh; // first activating clanhall function is payed from player inventory, any others from clan warehouse
public ClanHallFunction(int type, int lvl, int lease, int tempLease, long rate, long time, boolean cwh)
{
_type = type;
_lvl = lvl;
_fee = lease;
_tempFee = tempLease;
_rate = rate;
_endDate = time;
initializeTask(cwh);
}
public int getType()
{
return _type;
}
public int getLvl()
{
return _lvl;
}
public int getLease()
{
return _fee;
}
public long getRate()
{
return _rate;
}
public long getEndTime()
{
return _endDate;
}
public void setLvl(int lvl)
{
_lvl = lvl;
}
public void setLease(int lease)
{
_fee = lease;
}
public void setEndTime(long time)
{
_endDate = time;
}
private void initializeTask(boolean cwh)
{
if (_isFree)
{
return;
}
long currentTime = System.currentTimeMillis();
if (_endDate > currentTime)
{
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
}
}
private class FunctionTask implements Runnable
{
public FunctionTask(boolean cwh)
{
_cwh = cwh;
}
@Override
public void run()
{
try
{
if (_isFree)
{
return;
}
if ((ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().getAdena() >= _fee) || !_cwh)
{
int fee = _fee;
if (getEndTime() == -1)
{
fee = _tempFee;
}
setEndTime(System.currentTimeMillis() + getRate());
dbSave();
if (_cwh)
{
ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CH_function_fee", 57, fee, null, null);
if (Config.DEBUG)
{
_log.warning("deducted " + fee + " adena from " + getName() + " owner's cwh for function id : " + getType());
}
}
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
}
else
{
removeFunction(getType());
}
}
catch (Exception e)
{
_log.log(Level.SEVERE, "", e);
}
}
}
public void dbSave()
{
Connection con = null;
try
{
PreparedStatement statement;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("REPLACE INTO clanhall_functions (hall_id, type, lvl, lease, rate, endTime) VALUES (?,?,?,?,?,?)");
statement.setInt(1, getId());
statement.setInt(2, getType());
statement.setInt(3, getLvl());
statement.setInt(4, getLease());
statement.setLong(5, getRate());
statement.setLong(6, getEndTime());
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: ClanHall.updateFunctions(int type, int lvl, int lease, long rate, long time, boolean addNew): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
}
public ClanHall(int clanHallId, String name, int ownerId, int lease, String desc, String location, long paidUntil, int Grade, boolean paid)
{
_clanHallId = clanHallId;
_name = name;
_ownerId = ownerId;
if (Config.DEBUG)
{
_log.warning("Init Owner : " + _ownerId);
}
_lease = lease;
_desc = desc;
_location = location;
_paidUntil = paidUntil;
_grade = Grade;
_paid = paid;
_doorDefault = new FastList<>();
_functions = new FastMap<>();
if (ownerId != 0)
{
_isFree = false;
initialyzeTask(false);
loadFunctions();
}
}
/** Return if clanHall is paid or not */
public final boolean getPaid()
{
return _paid;
}
/** Return Id Of Clan hall */
public final int getId()
{
return _clanHallId;
}
/** Return name */
public final String getName()
{
return _name;
}
/** Return OwnerId */
public final int getOwnerId()
{
return _ownerId;
}
/** Return lease */
public final int getLease()
{
return _lease;
}
/** Return Desc */
public final String getDesc()
{
return _desc;
}
/** Return Location */
public final String getLocation()
{
return _location;
}
/** Return PaidUntil */
public final long getPaidUntil()
{
return _paidUntil;
}
/** Return Grade */
public final int getGrade()
{
return _grade;
}
/** Return all DoorInstance */
public final List<L2DoorInstance> getDoors()
{
if (_doors == null)
{
_doors = new FastList<>();
}
return _doors;
}
/** Return Door */
public final L2DoorInstance getDoor(int doorId)
{
if (doorId <= 0)
{
return null;
}
for (L2DoorInstance door : getDoors())
{
if (door.getDoorId() == doorId)
{
return door;
}
}
return null;
}
/** Return function with id */
public ClanHallFunction getFunction(int type)
{
if (_functions.get(type) != null)
{
return _functions.get(type);
}
return null;
}
/**
* Sets this clan halls zone
* @param zone
*/
public void setZone(L2ClanHallZone zone)
{
_zone = zone;
}
/** Returns the zone of this clan hall */
public L2ClanHallZone getZone()
{
return _zone;
}
/** Free this clan hall */
public void free()
{
_ownerId = 0;
_isFree = true;
for (Map.Entry<Integer, ClanHallFunction> fc : _functions.entrySet())
{
removeFunction(fc.getKey());
}
_functions.clear();
_paidUntil = 0;
_paid = false;
updateDb();
}
/** Set owner if clan hall is free */
public void setOwner(L2Clan clan)
{
// Verify that this ClanHall is Free and Clan isn't null
if ((_ownerId > 0) || (clan == null))
{
return;
}
_ownerId = clan.getClanId();
_isFree = false;
_paidUntil = System.currentTimeMillis();
initialyzeTask(true);
// Annonce to Online member new ClanHall
clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
updateDb();
}
/** Respawn all doors */
public void spawnDoor()
{
spawnDoor(false);
}
/** Respawn all doors */
public void spawnDoor(boolean isDoorWeak)
{
for (int i = 0; i < getDoors().size(); i++)
{
L2DoorInstance door = getDoors().get(i);
if (door.getCurrentHp() <= 0)
{
door.decayMe(); // Kill current if not killed already
door = DoorTable.parseList(_doorDefault.get(i), false);
DoorTable.getInstance().putDoor(door); // Readd the new door to the DoorTable By Erb
if (isDoorWeak)
{
door.setCurrentHp(door.getMaxHp() / 2);
}
door.spawnMe(door.getX(), door.getY(), door.getZ());
getDoors().set(i, door);
}
else if (door.getOpen())
{
door.closeMe();
}
}
}
/** Open or Close Door */
public void openCloseDoor(L2PcInstance activeChar, int doorId, boolean open)
{
if ((activeChar != null) && (activeChar.getClanId() == getOwnerId()))
{
openCloseDoor(doorId, open);
}
}
public void openCloseDoor(int doorId, boolean open)
{
openCloseDoor(getDoor(doorId), open);
}
public void openCloseDoor(L2DoorInstance door, boolean open)
{
if (door != null)
{
if (open)
{
door.openMe();
}
else
{
door.closeMe();
}
}
}
public void openCloseDoors(L2PcInstance activeChar, boolean open)
{
if ((activeChar != null) && (activeChar.getClanId() == getOwnerId()))
{
openCloseDoors(open);
}
}
public void openCloseDoors(boolean open)
{
for (L2DoorInstance door : getDoors())
{
if (door != null)
{
if (open)
{
door.openMe();
}
else
{
door.closeMe();
}
}
}
}
/** Banish Foreigner */
public void banishForeigners()
{
_zone.banishForeigners(getOwnerId());
}
/** Load All Functions */
private void loadFunctions()
{
Connection con = null;
try
{
PreparedStatement statement;
ResultSet rs;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("Select * from clanhall_functions where hall_id = ?");
statement.setInt(1, getId());
rs = statement.executeQuery();
while (rs.next())
{
_functions.put(rs.getInt("type"), new ClanHallFunction(rs.getInt("type"), rs.getInt("lvl"), rs.getInt("lease"), 0, rs.getLong("rate"), rs.getLong("endTime"), true));
}
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: ClanHall.loadFunctions(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Remove function In List and in DB */
public void removeFunction(int functionType)
{
_functions.remove(functionType);
Connection con = null;
try
{
PreparedStatement statement;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("DELETE FROM clanhall_functions WHERE hall_id=? AND type=?");
statement.setInt(1, getId());
statement.setInt(2, functionType);
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: ClanHall.removeFunctions(int functionType): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
public boolean updateFunctions(L2PcInstance player, int type, int lvl, int lease, long rate, boolean addNew)
{
if (player == null)
{
return false;
}
if (Config.DEBUG)
{
_log.warning("Called ClanHall.updateFunctions(int type, int lvl, int lease, long rate, boolean addNew) Owner : " + getOwnerId());
}
if (lease > 0)
{
if (!player.destroyItemByItemId("Consume", 57, lease, null, true))
{
return false;
}
}
if (addNew)
{
_functions.put(type, new ClanHallFunction(type, lvl, lease, 0, rate, 0, false));
}
else
{
if ((lvl == 0) && (lease == 0))
{
removeFunction(type);
}
else
{
int diffLease = lease - _functions.get(type).getLease();
if (Config.DEBUG)
{
_log.warning("Called ClanHall.updateFunctions diffLease : " + diffLease);
}
if (diffLease > 0)
{
_functions.remove(type);
_functions.put(type, new ClanHallFunction(type, lvl, lease, 0, rate, -1, false));
}
else
{
_functions.get(type).setLease(lease);
_functions.get(type).setLvl(lvl);
_functions.get(type).dbSave();
}
}
}
return true;
}
/** Update DB */
public void updateDb()
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
statement = con.prepareStatement("UPDATE clanhall SET ownerId=?, paidUntil=?, paid=? WHERE id=?");
statement.setInt(1, _ownerId);
statement.setLong(2, _paidUntil);
statement.setInt(3, (_paid) ? 1 : 0);
statement.setInt(4, _clanHallId);
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
/** Initialize Fee Task */
private void initialyzeTask(boolean forced)
{
long currentTime = System.currentTimeMillis();
if (_paidUntil > currentTime)
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), _paidUntil - currentTime);
}
else if (!_paid && !forced)
{
if ((System.currentTimeMillis() + (1000 * 60 * 60 * 24)) <= (_paidUntil + _chRate))
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), System.currentTimeMillis() + (1000 * 60 * 60 * 24));
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), (_paidUntil + _chRate) - System.currentTimeMillis());
}
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), 0);
}
}
/** Fee Task */
private class FeeTask implements Runnable
{
public FeeTask()
{
}
@Override
public void run()
{
try
{
long _time = System.currentTimeMillis();
if (_isFree)
{
return;
}
if (_paidUntil > _time)
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), _paidUntil - _time);
return;
}
L2Clan Clan = ClanTable.getInstance().getClan(getOwnerId());
if (ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().getAdena() >= getLease())
{
if (_paidUntil != 0)
{
while (_paidUntil <= _time)
{
_paidUntil += _chRate;
}
}
else
{
_paidUntil = _time + _chRate;
}
ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CH_rental_fee", 57, getLease(), null, null);
if (Config.DEBUG)
{
_log.warning("deducted " + getLease() + " adena from " + getName() + " owner's cwh for ClanHall _paidUntil: " + _paidUntil);
}
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), _paidUntil - _time);
_paid = true;
updateDb();
}
else
{
_paid = false;
if (_time > (_paidUntil + _chRate))
{
if (ClanHallManager.getInstance().loaded())
{
AuctionManager.getInstance().initNPC(getId());
ClanHallManager.getInstance().setFree(getId());
Clan.broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.THE_CLAN_HALL_FEE_IS_ONE_WEEK_OVERDUE_THEREFORE_THE_CLAN_HALL_OWNERSHIP_HAS_BEEN_REVOKED));
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), 3000);
}
}
else
{
updateDb();
SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.PAYMENT_FOR_YOUR_CLAN_HALL_HAS_NOT_BEEN_MADE_PLEASE_MAKE_PAYMENT_TO_YOUR_CLAN_WAREHOUSE_BY_S1_TOMORROW);
sm.addNumber(getLease());
Clan.broadcastToOnlineMembers(sm);
if ((_time + (1000 * 60 * 60 * 24)) <= (_paidUntil + _chRate))
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), _time + (1000 * 60 * 60 * 24));
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FeeTask(), (_paidUntil + _chRate) - _time);
}
}
}
}
catch (Exception e)
{
_log.log(Level.SEVERE, "", e);
}
}
}
}
@@ -0,0 +1,205 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.idfactory.IdFactory;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
/**
* @author evill33t
*/
public class Couple
{
private static final Logger _log = Logger.getLogger(Couple.class.getName());
// =========================================================
// Data Field
private int _Id = 0;
private int _player1Id = 0;
private int _player2Id = 0;
private boolean _maried = false;
private Calendar _affiancedDate;
private Calendar _weddingDate;
// =========================================================
// Constructor
public Couple(int coupleId)
{
_Id = coupleId;
Connection con = null;
try
{
PreparedStatement statement;
ResultSet rs;
con = L2DatabaseFactory.getInstance().getConnection();
statement = con.prepareStatement("SELECT * FROM mods_wedding WHERE id = ?");
statement.setInt(1, _Id);
rs = statement.executeQuery();
while (rs.next())
{
_player1Id = rs.getInt("player1Id");
_player2Id = rs.getInt("player2Id");
_maried = rs.getBoolean("married");
_affiancedDate = Calendar.getInstance();
_affiancedDate.setTimeInMillis(rs.getLong("affianceDate"));
_weddingDate = Calendar.getInstance();
_weddingDate.setTimeInMillis(rs.getLong("weddingDate"));
}
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Couple.load(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
public Couple(L2PcInstance player1, L2PcInstance player2)
{
int _tempPlayer1Id = player1.getObjectId();
int _tempPlayer2Id = player2.getObjectId();
_player1Id = _tempPlayer1Id;
_player2Id = _tempPlayer2Id;
_affiancedDate = Calendar.getInstance();
_affiancedDate.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
_weddingDate = Calendar.getInstance();
_weddingDate.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
_Id = IdFactory.getInstance().getNextId();
statement = con.prepareStatement("INSERT INTO mods_wedding (id, player1Id, player2Id, married, affianceDate, weddingDate) VALUES (?, ?, ?, ?, ?, ?)");
statement.setInt(1, _Id);
statement.setInt(2, _player1Id);
statement.setInt(3, _player2Id);
statement.setBoolean(4, false);
statement.setLong(5, _affiancedDate.getTimeInMillis());
statement.setLong(6, _weddingDate.getTimeInMillis());
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Could not create couple: " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
public void marry()
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
statement = con.prepareStatement("UPDATE mods_wedding set married = ?, weddingDate = ? where id = ?");
statement.setBoolean(1, true);
_weddingDate = Calendar.getInstance();
statement.setLong(2, _weddingDate.getTimeInMillis());
statement.setInt(3, _Id);
statement.execute();
statement.close();
_maried = true;
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Could not marry: " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
public void divorce()
{
Connection con = null;
try
{
con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM mods_wedding WHERE id=?");
statement.setInt(1, _Id);
statement.execute();
statement.close();
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Exception: Couple.divorce(): " + e.getMessage(), e);
}
finally
{
L2DatabaseFactory.close(con);
}
}
public final int getId()
{
return _Id;
}
public final int getPlayer1Id()
{
return _player1Id;
}
public final int getPlayer2Id()
{
return _player2Id;
}
public final boolean getMaried()
{
return _maried;
}
public final Calendar getAffiancedDate()
{
return _affiancedDate;
}
public final Calendar getWeddingDate()
{
return _weddingDate;
}
}
@@ -0,0 +1,483 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Future;
import javolution.util.FastList;
import com.l2jserver.Config;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.instancemanager.DimensionalRiftManager;
import com.l2jserver.gameserver.instancemanager.QuestManager;
import com.l2jserver.gameserver.model.L2Party;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
import com.l2jserver.gameserver.network.serverpackets.Earthquake;
import com.l2jserver.util.Rnd;
/**
* Thanks to L2Fortress and balancer.ru - kombat
*/
public class DimensionalRift
{
protected byte _type;
protected L2Party _party;
protected FastList<Byte> _completedRooms = new FastList<>();
private static final long seconds_5 = 5000L;
// private static final int MILLISECONDS_IN_MINUTE = 60000;
protected byte jumps_current = 0;
private Timer teleporterTimer;
private TimerTask teleporterTimerTask;
private Timer spawnTimer;
private TimerTask spawnTimerTask;
private Future<?> earthQuakeTask;
protected byte _choosenRoom = -1;
private boolean _hasJumped = false;
protected FastList<L2PcInstance> deadPlayers = new FastList<>();
protected FastList<L2PcInstance> revivedInWaitingRoom = new FastList<>();
private boolean isBossRoom = false;
// private final static Log _log = LogFactory.getLog(DimensionalRift.class.getName());
public DimensionalRift(L2Party party, byte type, byte room)
{
DimensionalRiftManager.getInstance().getRoom(type, room).setPartyInside(true);
_type = type;
_party = party;
_choosenRoom = room;
int[] coords = getRoomCoord(room);
party.setDimensionalRift(this);
for (L2PcInstance p : party.getPartyMembers())
{
Quest riftQuest = QuestManager.getInstance().getQuest(635);
if (riftQuest != null)
{
QuestState qs = p.getQuestState(riftQuest.getName());
if (qs == null)
{
qs = riftQuest.newQuestState(p);
}
if (qs.getInt("cond") != 1)
{
qs.set("cond", "1");
}
}
p.teleToLocation(coords[0], coords[1], coords[2]);
}
createSpawnTimer(_choosenRoom);
createTeleporterTimer(true);
}
public byte getType()
{
return _type;
}
public byte getCurrentRoom()
{
return _choosenRoom;
}
protected void createTeleporterTimer(final boolean reasonTP)
{
if (teleporterTimerTask != null)
{
teleporterTimerTask.cancel();
teleporterTimerTask = null;
}
if (teleporterTimer != null)
{
teleporterTimer.cancel();
teleporterTimer = null;
}
if (earthQuakeTask != null)
{
earthQuakeTask.cancel(false);
earthQuakeTask = null;
}
teleporterTimer = new Timer();
teleporterTimerTask = new TimerTask()
{
@Override
public void run()
{
if (_choosenRoom > -1)
{
DimensionalRiftManager.getInstance().getRoom(_type, _choosenRoom).unspawn().setPartyInside(false);
}
if (reasonTP && (jumps_current < getMaxJumps()) && (_party.getMemberCount() > deadPlayers.size()))
{
jumps_current++;
_completedRooms.add(_choosenRoom);
_choosenRoom = -1;
for (L2PcInstance p : _party.getPartyMembers())
{
if (!revivedInWaitingRoom.contains(p))
{
teleportToNextRoom(p);
}
}
createTeleporterTimer(true);
createSpawnTimer(_choosenRoom);
}
else
{
for (L2PcInstance p : _party.getPartyMembers())
{
if (!revivedInWaitingRoom.contains(p))
{
teleportToWaitingRoom(p);
}
}
killRift();
cancel();
}
}
};
if (reasonTP)
{
long jumpTime = calcTimeToNextJump();
teleporterTimer.schedule(teleporterTimerTask, jumpTime); // Teleporter task, 8-10 minutes
earthQuakeTask = ThreadPoolManager.getInstance().scheduleGeneral(() ->
{
for (L2PcInstance p : _party.getPartyMembers())
{
if (!revivedInWaitingRoom.contains(p))
{
p.sendPacket(new Earthquake(p.getX(), p.getY(), p.getZ(), 65, 9));
}
}
}, jumpTime - 7000);
}
else
{
teleporterTimer.schedule(teleporterTimerTask, seconds_5); // incorrect party member invited.
}
}
public void createSpawnTimer(final byte room)
{
if (spawnTimerTask != null)
{
spawnTimerTask.cancel();
spawnTimerTask = null;
}
if (spawnTimer != null)
{
spawnTimer.cancel();
spawnTimer = null;
}
spawnTimer = new Timer();
spawnTimerTask = new TimerTask()
{
@Override
public void run()
{
DimensionalRiftManager.getInstance().getRoom(_type, room).spawn();
}
};
spawnTimer.schedule(spawnTimerTask, Config.RIFT_SPAWN_DELAY);
}
public void partyMemberInvited()
{
createTeleporterTimer(false);
}
public void partyMemberExited(L2PcInstance player)
{
if (deadPlayers.contains(player))
{
deadPlayers.remove(player);
}
if (revivedInWaitingRoom.contains(player))
{
revivedInWaitingRoom.remove(player);
}
if ((_party.getMemberCount() < Config.RIFT_MIN_PARTY_SIZE) || (_party.getMemberCount() == 1))
{
for (L2PcInstance p : _party.getPartyMembers())
{
teleportToWaitingRoom(p);
}
killRift();
}
}
public void manualTeleport(L2PcInstance player, L2Npc npc)
{
if (!player.isInParty() || !player.getParty().isInDimensionalRift())
{
return;
}
if (player.getObjectId() != player.getParty().getPartyLeaderOID())
{
DimensionalRiftManager.getInstance().showHtmlFile(player, "data/html/seven_signs/rift/NotPartyLeader.htm", npc);
return;
}
if (_hasJumped)
{
DimensionalRiftManager.getInstance().showHtmlFile(player, "data/html/seven_signs/rift/AlreadyTeleported.htm", npc);
return;
}
_hasJumped = true;
DimensionalRiftManager.getInstance().getRoom(_type, _choosenRoom).unspawn().setPartyInside(false);
_completedRooms.add(_choosenRoom);
_choosenRoom = -1;
for (L2PcInstance p : _party.getPartyMembers())
{
teleportToNextRoom(p);
}
DimensionalRiftManager.getInstance().getRoom(_type, _choosenRoom).setPartyInside(true);
createSpawnTimer(_choosenRoom);
createTeleporterTimer(true);
}
public void manualExitRift(L2PcInstance player, L2Npc npc)
{
if (!player.isInParty() || !player.getParty().isInDimensionalRift())
{
return;
}
if (player.getObjectId() != player.getParty().getPartyLeaderOID())
{
DimensionalRiftManager.getInstance().showHtmlFile(player, "data/html/seven_signs/rift/NotPartyLeader.htm", npc);
return;
}
for (L2PcInstance p : player.getParty().getPartyMembers())
{
teleportToWaitingRoom(p);
}
killRift();
}
protected void teleportToNextRoom(L2PcInstance player)
{
if (_choosenRoom == -1)
{
FastList<Byte> emptyRooms;
do
{
emptyRooms = DimensionalRiftManager.getInstance().getFreeRooms(_type);
// Do not tp in the same room a second time
emptyRooms.removeAll(_completedRooms);
// If no room left, find any empty
if (emptyRooms.isEmpty())
{
emptyRooms = DimensionalRiftManager.getInstance().getFreeRooms(_type);
}
_choosenRoom = emptyRooms.get(Rnd.get(1, emptyRooms.size()) - 1);
}
while (DimensionalRiftManager.getInstance().getRoom(_type, _choosenRoom).ispartyInside());
}
DimensionalRiftManager.getInstance().getRoom(_type, _choosenRoom).setPartyInside(true);
checkBossRoom(_choosenRoom);
int[] coords = getRoomCoord(_choosenRoom);
player.teleToLocation(coords[0], coords[1], coords[2]);
}
protected void teleportToWaitingRoom(L2PcInstance player)
{
DimensionalRiftManager.getInstance().teleportToWaitingRoom(player);
Quest riftQuest = QuestManager.getInstance().getQuest(635);
if (riftQuest != null)
{
QuestState qs = player.getQuestState(riftQuest.getName());
if ((qs != null) && (qs.getInt("cond") == 1))
{
qs.set("cond", "0");
}
}
}
public void killRift()
{
_completedRooms = null;
if (_party != null)
{
_party.setDimensionalRift(null);
}
_party = null;
revivedInWaitingRoom = null;
deadPlayers = null;
if (earthQuakeTask != null)
{
earthQuakeTask.cancel(false);
earthQuakeTask = null;
}
DimensionalRiftManager.getInstance().getRoom(_type, _choosenRoom).unspawn().setPartyInside(false);
DimensionalRiftManager.getInstance().killRift(this);
}
public Timer getTeleportTimer()
{
return teleporterTimer;
}
public TimerTask getTeleportTimerTask()
{
return teleporterTimerTask;
}
public Timer getSpawnTimer()
{
return spawnTimer;
}
public TimerTask getSpawnTimerTask()
{
return spawnTimerTask;
}
public void setTeleportTimer(Timer t)
{
teleporterTimer = t;
}
public void setTeleportTimerTask(TimerTask tt)
{
teleporterTimerTask = tt;
}
public void setSpawnTimer(Timer t)
{
spawnTimer = t;
}
public void setSpawnTimerTask(TimerTask st)
{
spawnTimerTask = st;
}
private long calcTimeToNextJump()
{
int time = Rnd.get(Config.RIFT_AUTO_JUMPS_TIME_MIN, Config.RIFT_AUTO_JUMPS_TIME_MAX) * 1000;
if (isBossRoom)
{
return (long) (time * Config.RIFT_BOSS_ROOM_TIME_MUTIPLY);
}
return time;
}
public void memberDead(L2PcInstance player)
{
if (!deadPlayers.contains(player))
{
deadPlayers.add(player);
}
}
public void memberRessurected(L2PcInstance player)
{
if (deadPlayers.contains(player))
{
deadPlayers.remove(player);
}
}
public void usedTeleport(L2PcInstance player)
{
if (!revivedInWaitingRoom.contains(player))
{
revivedInWaitingRoom.add(player);
}
if (!deadPlayers.contains(player))
{
deadPlayers.add(player);
}
if ((_party.getMemberCount() - revivedInWaitingRoom.size()) < Config.RIFT_MIN_PARTY_SIZE)
{
// int pcm = _party.getMemberCount();
// int rev = revivedInWaitingRoom.size();
// int min = Config.RIFT_MIN_PARTY_SIZE;
for (L2PcInstance p : _party.getPartyMembers())
{
if ((p != null) && !revivedInWaitingRoom.contains(p))
{
teleportToWaitingRoom(p);
}
}
killRift();
}
}
public FastList<L2PcInstance> getDeadMemberList()
{
return deadPlayers;
}
public FastList<L2PcInstance> getRevivedAtWaitingRoom()
{
return revivedInWaitingRoom;
}
public void checkBossRoom(byte room)
{
isBossRoom = DimensionalRiftManager.getInstance().getRoom(_type, room).isBossRoom();
}
public int[] getRoomCoord(byte room)
{
return DimensionalRiftManager.getInstance().getRoom(_type, room).getTeleportCoords();
}
public byte getMaxJumps()
{
if ((Config.RIFT_MAX_JUMPS <= 8) && (Config.RIFT_MAX_JUMPS >= 1))
{
return (byte) Config.RIFT_MAX_JUMPS;
}
return 4;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,744 @@
package com.l2jserver.gameserver.model.entity;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntProcedure;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javolution.util.FastList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.l2jserver.Config;
import com.l2jserver.gameserver.Announcements;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.datatables.DoorTable;
import com.l2jserver.gameserver.datatables.MapRegionTable;
import com.l2jserver.gameserver.datatables.NpcTable;
import com.l2jserver.gameserver.idfactory.IdFactory;
import com.l2jserver.gameserver.instancemanager.InstanceManager;
import com.l2jserver.gameserver.model.L2Spawn;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.L2WorldRegion;
import com.l2jserver.gameserver.model.actor.L2Attackable;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.clientpackets.Say2;
import com.l2jserver.gameserver.network.serverpackets.CreatureSay;
import com.l2jserver.gameserver.network.serverpackets.L2GameServerPacket;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.templates.chars.L2NpcTemplate;
/**
* @author evill33t, GodKratos
*/
public class Instance
{
private final static Logger _log = Logger.getLogger(Instance.class.getName());
private final int _id;
private String _name;
private final TIntHashSet _players = new TIntHashSet();
private final EjectPlayerProcedure _ejectProc;
private final FastList<L2Npc> _npcs = new FastList<L2Npc>().shared();
private ArrayList<L2DoorInstance> _doors = null;
private int[] _spawnLoc = new int[3];
private boolean _allowSummon = true;
private long _emptyDestroyTime = -1;
private long _lastLeft = -1;
private long _instanceStartTime = -1;
private long _instanceEndTime = -1;
private boolean _isPvPInstance = false;
private boolean _showTimer = false;
private boolean _isTimerIncrease = true;
private String _timerText = "";
protected ScheduledFuture<?> _CheckTimeUpTask = null;
public Instance(int id)
{
_id = id;
_ejectProc = new EjectPlayerProcedure();
_instanceStartTime = System.currentTimeMillis();
}
/**
* Returns the ID of this instance.
*/
public int getId()
{
return _id;
}
/**
* Returns the name of this instance
*/
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
/**
* Returns whether summon friend type skills are allowed for this instance
*/
public boolean isSummonAllowed()
{
return _allowSummon;
}
/**
* Sets the status for the instance for summon friend type skills
*/
public void setAllowSummon(boolean b)
{
_allowSummon = b;
}
/*
* Returns true if entire instance is PvP zone
*/
public boolean isPvPInstance()
{
return _isPvPInstance;
}
/*
* Sets PvP zone status of the instance
*/
public void setPvPInstance(boolean b)
{
_isPvPInstance = b;
}
/**
* Set the instance duration task
* @param duration in milliseconds
*/
public void setDuration(int duration)
{
if (_CheckTimeUpTask != null)
{
_CheckTimeUpTask.cancel(true);
}
_CheckTimeUpTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckTimeUp(duration), 500);
_instanceEndTime = System.currentTimeMillis() + duration + 500;
}
/**
* Set time before empty instance will be removed
* @param time in milliseconds
*/
public void setEmptyDestroyTime(long time)
{
_emptyDestroyTime = time;
}
/**
* Checks if the player exists within this instance
* @param objectId
* @return true if player exists in instance
*/
public boolean containsPlayer(int objectId)
{
return _players.contains(objectId);
}
/**
* Adds the specified player to the instance
* @param objectId Players object ID
*/
public void addPlayer(int objectId)
{
synchronized (_players)
{
_players.add(objectId);
}
}
/**
* Removes the specified player from the instance list
* @param objectId Players object ID
*/
public void removePlayer(int objectId)
{
synchronized (_players)
{
_players.remove(objectId);
}
if (_players.isEmpty() && (_emptyDestroyTime >= 0))
{
_lastLeft = System.currentTimeMillis();
setDuration((int) (_instanceEndTime - System.currentTimeMillis() - 500));
}
}
/**
* Removes the player from the instance by setting InstanceId to 0 and teleporting to nearest town.
* @param objectId
*/
public void ejectPlayer(int objectId)
{
L2PcInstance player = L2World.getInstance().getPlayer(objectId);
if ((player != null) && (player.getInstanceId() == getId()))
{
player.setInstanceId(0);
player.sendMessage("You were removed from the instance");
if ((getSpawnLoc()[0] != 0) && (getSpawnLoc()[1] != 0) && (getSpawnLoc()[2] != 0))
{
player.teleToLocation(getSpawnLoc()[0], getSpawnLoc()[1], getSpawnLoc()[2]);
}
else
{
player.teleToLocation(MapRegionTable.TeleportWhereType.Town);
}
}
}
public void addNpc(L2Npc npc)
{
_npcs.add(npc);
}
public void removeNpc(L2Npc npc)
{
if (npc.getSpawn() != null)
{
npc.getSpawn().stopRespawn();
}
// npc.deleteMe();
_npcs.remove(npc);
}
/**
* Adds a door into the instance
* @param doorId - from doors.csv
* @param open - initial state of the door
*/
private void addDoor(int doorId, boolean open)
{
if (_doors == null)
{
_doors = new ArrayList<>(2);
}
for (L2DoorInstance door : _doors)
{
if (door.getDoorId() == doorId)
{
_log.warning("Door ID " + doorId + " already exists in instance " + getId());
return;
}
}
L2DoorInstance temp = DoorTable.getInstance().getDoor(doorId);
L2DoorInstance newdoor = new L2DoorInstance(IdFactory.getInstance().getNextId(), temp.getTemplate(), temp.getDoorId(), temp.getName(), temp.isUnlockable());
newdoor.setInstanceId(getId());
newdoor.setRange(temp.getXMin(), temp.getYMin(), temp.getZMin(), temp.getXMax(), temp.getYMax(), temp.getZMax());
try
{
newdoor.setMapRegion(MapRegionTable.getInstance().getMapRegion(temp.getX(), temp.getY()));
}
catch (Exception e)
{
_log.severe("Error in door data, ID:" + temp.getDoorId());
}
newdoor.getStatus().setCurrentHpMp(newdoor.getMaxHp(), newdoor.getMaxMp());
newdoor.setOpen(open);
newdoor.getPosition().setXYZInvisible(temp.getX(), temp.getY(), temp.getZ());
newdoor.spawnMe(newdoor.getX(), newdoor.getY(), newdoor.getZ());
newdoor.setEmitter(temp.getEmitter());
newdoor.setTargetable(temp.getTargetable());
newdoor.setMeshIndex(temp.getMeshIndex());
_doors.add(newdoor);
}
public TIntHashSet getPlayers()
{
return _players;
}
public FastList<L2Npc> getNpcs()
{
return _npcs;
}
public ArrayList<L2DoorInstance> getDoors()
{
return _doors;
}
public L2DoorInstance getDoor(int id)
{
for (L2DoorInstance temp : getDoors())
{
if (temp.getDoorId() == id)
{
return temp;
}
}
return null;
}
public long getInstanceEndTime()
{
return _instanceEndTime;
}
public long getInstanceStartTime()
{
return _instanceStartTime;
}
public boolean isShowTimer()
{
return _showTimer;
}
public boolean isTimerIncrease()
{
return _isTimerIncrease;
}
public String getTimerText()
{
return _timerText;
}
/**
* Returns the spawn location for this instance to be used when leaving the instance
* @return int[3]
*/
public int[] getSpawnLoc()
{
return _spawnLoc;
}
/**
* Sets the spawn location for this instance to be used when leaving the instance
*/
public void setSpawnLoc(int[] loc)
{
if ((loc == null) || (loc.length < 3))
{
return;
}
System.arraycopy(loc, 0, _spawnLoc, 0, 3);
}
public void removePlayers()
{
_players.forEach(_ejectProc);
synchronized (_players)
{
_players.clear();
}
}
public void removeNpcs()
{
for (L2Npc mob : _npcs)
{
if (mob != null)
{
if (mob.getSpawn() != null)
{
mob.getSpawn().stopRespawn();
}
mob.deleteMe();
}
}
_npcs.clear();
}
public void removeDoors()
{
if (_doors == null)
{
return;
}
for (L2DoorInstance door : _doors)
{
if (door != null)
{
L2WorldRegion region = door.getWorldRegion();
door.decayMe();
if (region != null)
{
region.removeVisibleObject(door);
}
door.getKnownList().removeAllKnownObjects();
L2World.getInstance().removeObject(door);
}
}
_doors.clear();
_doors = null;
}
public void loadInstanceTemplate(String filename)
{
Document doc = null;
File xml = new File(Config.DATAPACK_ROOT, "data/instances/" + filename);
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
doc = factory.newDocumentBuilder().parse(xml);
for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
{
if ("instance".equalsIgnoreCase(n.getNodeName()))
{
parseInstance(n);
}
}
}
catch (IOException e)
{
_log.log(Level.WARNING, "Instance: can not find " + xml.getAbsolutePath() + " ! " + e.getMessage(), e);
}
catch (Exception e)
{
_log.log(Level.WARNING, "Instance: error while loading " + xml.getAbsolutePath() + " ! " + e.getMessage(), e);
}
}
private void parseInstance(Node n) throws Exception
{
L2Spawn spawnDat;
L2NpcTemplate npcTemplate;
String name = null;
name = n.getAttributes().getNamedItem("name").getNodeValue();
setName(name);
Node a;
Node first = n.getFirstChild();
for (n = first; n != null; n = n.getNextSibling())
{
if ("activityTime".equalsIgnoreCase(n.getNodeName()))
{
a = n.getAttributes().getNamedItem("val");
if (a != null)
{
_CheckTimeUpTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckTimeUp(Integer.parseInt(a.getNodeValue()) * 60000), 15000);
_instanceEndTime = System.currentTimeMillis() + (Long.parseLong(a.getNodeValue()) * 60000) + 15000;
}
}
/*
* else if ("timeDelay".equalsIgnoreCase(n.getNodeName())) { a = n.getAttributes().getNamedItem("val"); if (a != null) instance.setTimeDelay(Integer.parseInt(a.getNodeValue())); }
*/
else if ("allowSummon".equalsIgnoreCase(n.getNodeName()))
{
a = n.getAttributes().getNamedItem("val");
if (a != null)
{
setAllowSummon(Boolean.parseBoolean(a.getNodeValue()));
}
}
else if ("emptyDestroyTime".equalsIgnoreCase(n.getNodeName()))
{
a = n.getAttributes().getNamedItem("val");
if (a != null)
{
_emptyDestroyTime = Long.parseLong(a.getNodeValue()) * 1000;
}
}
else if ("showTimer".equalsIgnoreCase(n.getNodeName()))
{
a = n.getAttributes().getNamedItem("val");
if (a != null)
{
_showTimer = Boolean.parseBoolean(a.getNodeValue());
}
a = n.getAttributes().getNamedItem("increase");
if (a != null)
{
_isTimerIncrease = Boolean.parseBoolean(a.getNodeValue());
}
a = n.getAttributes().getNamedItem("text");
if (a != null)
{
_timerText = a.getNodeValue();
}
}
else if ("PvPInstance".equalsIgnoreCase(n.getNodeName()))
{
a = n.getAttributes().getNamedItem("val");
if (a != null)
{
setPvPInstance(Boolean.parseBoolean(a.getNodeValue()));
}
}
else if ("doorlist".equalsIgnoreCase(n.getNodeName()))
{
for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
{
int doorId = 0;
boolean doorState = false;
if ("door".equalsIgnoreCase(d.getNodeName()))
{
doorId = Integer.parseInt(d.getAttributes().getNamedItem("doorId").getNodeValue());
if (d.getAttributes().getNamedItem("open") != null)
{
doorState = Boolean.parseBoolean(d.getAttributes().getNamedItem("open").getNodeValue());
}
addDoor(doorId, doorState);
}
}
}
else if ("spawnlist".equalsIgnoreCase(n.getNodeName()))
{
for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
{
int npcId = 0, x = 0, y = 0, z = 0, respawn = 0, heading = 0, delay = -1;
if ("spawn".equalsIgnoreCase(d.getNodeName()))
{
npcId = Integer.parseInt(d.getAttributes().getNamedItem("npcId").getNodeValue());
x = Integer.parseInt(d.getAttributes().getNamedItem("x").getNodeValue());
y = Integer.parseInt(d.getAttributes().getNamedItem("y").getNodeValue());
z = Integer.parseInt(d.getAttributes().getNamedItem("z").getNodeValue());
heading = Integer.parseInt(d.getAttributes().getNamedItem("heading").getNodeValue());
respawn = Integer.parseInt(d.getAttributes().getNamedItem("respawn").getNodeValue());
if (d.getAttributes().getNamedItem("onKillDelay") != null)
{
delay = Integer.parseInt(d.getAttributes().getNamedItem("onKillDelay").getNodeValue());
}
npcTemplate = NpcTable.getInstance().getTemplate(npcId);
if (npcTemplate != null)
{
spawnDat = new L2Spawn(npcTemplate);
spawnDat.setLocx(x);
spawnDat.setLocy(y);
spawnDat.setLocz(z);
spawnDat.setAmount(1);
spawnDat.setHeading(heading);
spawnDat.setRespawnDelay(respawn);
if (respawn == 0)
{
spawnDat.stopRespawn();
}
else
{
spawnDat.startRespawn();
}
spawnDat.setInstanceId(getId());
L2Npc spawned = spawnDat.doSpawn();
if ((delay >= 0) && (spawned instanceof L2Attackable))
{
((L2Attackable) spawned).setOnKillDelay(delay);
}
}
else
{
_log.warning("Instance: Data missing in NPC table for ID: " + npcId + " in Instance " + getId());
}
}
}
}
else if ("spawnpoint".equalsIgnoreCase(n.getNodeName()))
{
try
{
_spawnLoc[0] = Integer.parseInt(n.getAttributes().getNamedItem("spawnX").getNodeValue());
_spawnLoc[1] = Integer.parseInt(n.getAttributes().getNamedItem("spawnY").getNodeValue());
_spawnLoc[2] = Integer.parseInt(n.getAttributes().getNamedItem("spawnZ").getNodeValue());
}
catch (Exception e)
{
_log.log(Level.WARNING, "Error parsing instance xml: " + e.getMessage(), e);
_spawnLoc = new int[3];
}
}
}
if (Config.DEBUG)
{
_log.info(name + " Instance Template for Instance " + getId() + " loaded");
}
}
protected void doCheckTimeUp(int remaining)
{
CreatureSay cs = null;
int timeLeft;
int interval;
if (_players.isEmpty() && (_emptyDestroyTime == 0))
{
remaining = 0;
interval = 500;
}
else if (_players.isEmpty() && (_emptyDestroyTime > 0))
{
Long emptyTimeLeft = (_lastLeft + _emptyDestroyTime) - System.currentTimeMillis();
if (emptyTimeLeft <= 0)
{
interval = 0;
remaining = 0;
}
else if ((remaining > 300000) && (emptyTimeLeft > 300000))
{
interval = 300000;
remaining = remaining - 300000;
}
else if ((remaining > 60000) && (emptyTimeLeft > 60000))
{
interval = 60000;
remaining = remaining - 60000;
}
else if ((remaining > 30000) && (emptyTimeLeft > 30000))
{
interval = 30000;
remaining = remaining - 30000;
}
else
{
interval = 10000;
remaining = remaining - 10000;
}
}
else if (remaining > 300000)
{
timeLeft = remaining / 60000;
interval = 300000;
SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.DUNGEON_EXPIRES_IN_S1_MINUTES);
sm.addString(Integer.toString(timeLeft));
Announcements.getInstance().announceToInstance(sm, getId());
remaining = remaining - 300000;
}
else if (remaining > 60000)
{
timeLeft = remaining / 60000;
interval = 60000;
SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.DUNGEON_EXPIRES_IN_S1_MINUTES);
sm.addString(Integer.toString(timeLeft));
Announcements.getInstance().announceToInstance(sm, getId());
remaining = remaining - 60000;
}
else if (remaining > 30000)
{
timeLeft = remaining / 1000;
interval = 30000;
cs = new CreatureSay(0, Say2.ALLIANCE, "Notice", timeLeft + " seconds left.");
remaining = remaining - 30000;
}
else
{
timeLeft = remaining / 1000;
interval = 10000;
cs = new CreatureSay(0, Say2.ALLIANCE, "Notice", timeLeft + " seconds left.");
remaining = remaining - 10000;
}
if (cs != null)
{
_players.forEach(new SendPacketToPlayerProcedure(cs));
}
cancelTimer();
if (remaining >= 10000)
{
_CheckTimeUpTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckTimeUp(remaining), interval);
}
else
{
_CheckTimeUpTask = ThreadPoolManager.getInstance().scheduleGeneral(new TimeUp(), interval);
}
}
public void cancelTimer()
{
if (_CheckTimeUpTask != null)
{
_CheckTimeUpTask.cancel(true);
}
}
public class CheckTimeUp implements Runnable
{
private final int _remaining;
public CheckTimeUp(int remaining)
{
_remaining = remaining;
}
@Override
public void run()
{
doCheckTimeUp(_remaining);
}
}
public class TimeUp implements Runnable
{
@Override
public void run()
{
InstanceManager.getInstance().destroyInstance(getId());
}
}
private final class EjectPlayerProcedure implements TIntProcedure
{
EjectPlayerProcedure()
{
}
@Override
public final boolean execute(final int objId)
{
ejectPlayer(objId);
return true;
}
}
private final class SendPacketToPlayerProcedure implements TIntProcedure
{
private final L2GameServerPacket _packet;
SendPacketToPlayerProcedure(final L2GameServerPacket packet)
{
_packet = packet;
}
@Override
public final boolean execute(final int objId)
{
L2PcInstance player = L2World.getInstance().getPlayer(objId);
if (player.getInstanceId() == getId())
{
player.sendPacket(_packet);
}
return true;
}
}
}
@@ -0,0 +1,294 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jserver.gameserver.datatables.NpcTable;
import com.l2jserver.gameserver.datatables.SpawnTable;
import com.l2jserver.gameserver.model.L2Spawn;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.serverpackets.MagicSkillUse;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jserver.gameserver.templates.chars.L2NpcTemplate;
import com.l2jserver.gameserver.util.Broadcast;
import com.l2jserver.util.EventData;
import com.l2jserver.util.StringUtil;
/**
* This class ...
* @version $Revision: 1.3.4.1 $ $Date: 2005/03/27 15:29:32 $
*/
public class L2Event
{
protected static final Logger _log = Logger.getLogger(L2Event.class.getName());
public static String eventName = "";
public static int teamsNumber = 0;
public static final HashMap<Integer, String> names = new HashMap<>();
public static final LinkedList<String> participatingPlayers = new LinkedList<>(); // TODO store by objid
public static final HashMap<Integer, LinkedList<String>> players = new HashMap<>();
public static int id = 12760;
public static final LinkedList<String> npcs = new LinkedList<>();
public static boolean active = false;
public static final HashMap<String, EventData> connectionLossData = new HashMap<>();
public static int getTeamOfPlayer(String name)
{
for (int i = 1; i <= players.size(); i++)
{
LinkedList<String> temp = players.get(i);
Iterator<String> it = temp.iterator();
while (it.hasNext())
{
if (it.next().equals(name))
{
return i;
}
}
}
return 0;
}
public static String[] getTopNKillers(int N)
{ // this will return top N players sorted by kills, first element in the array will be the one with more kills
String[] killers = new String[N];
String playerTemp = "";
int kills = 0;
LinkedList<String> killersTemp = new LinkedList<>();
for (int k = 0; k < N; k++)
{
kills = 0;
for (int i = 1; i <= teamsNumber; i++)
{
LinkedList<String> temp = players.get(i);
Iterator<String> it = temp.iterator();
while (it.hasNext())
{
try
{
L2PcInstance player = L2World.getInstance().getPlayer(it.next());
if (!killersTemp.contains(player.getName()))
{
if (player.kills.size() > kills)
{
kills = player.kills.size();
playerTemp = player.getName();
}
}
}
catch (Exception e)
{
}
}
}
killersTemp.add(playerTemp);
}
for (int i = 0; i < N; i++)
{
kills = 0;
Iterator<String> it = killersTemp.iterator();
while (it.hasNext())
{
try
{
L2PcInstance player = L2World.getInstance().getPlayer(it.next());
if (player.kills.size() > kills)
{
kills = player.kills.size();
playerTemp = player.getName();
}
}
catch (Exception e)
{
}
}
killers[i] = playerTemp;
killersTemp.remove(playerTemp);
}
return killers;
}
public static void showEventHtml(L2PcInstance player, String objectid)
{
try
{
NpcHtmlMessage adminReply = new NpcHtmlMessage(5);
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("data/events/" + eventName)));
final StringBuilder replyMSG = new StringBuilder();
try (BufferedReader inbr = new BufferedReader(new InputStreamReader(in)))
{
StringUtil.append(replyMSG, "<html><body>" + "<center><font color=\"LEVEL\">", eventName, "</font><font color=\"FF0000\"> bY ", inbr.readLine(), "</font></center><br>" + "<br>", inbr.readLine());
}
if (L2Event.participatingPlayers.contains(player.getName()))
{
replyMSG.append("<br><center>You are already in the event players list !!</center></body></html>");
}
else
{
StringUtil.append(replyMSG, "<br><center><button value=\"Participate !! \" action=\"bypass -h npc_", String.valueOf(objectid), "_event_participate\" width=90 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></center></body></html>");
}
adminReply.setHtml(replyMSG.toString());
player.sendPacket(adminReply);
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception on showEventHtml(): " + e.getMessage(), e);
}
}
public static void spawn(L2PcInstance target, int npcid)
{
L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(npcid);
try
{
// L2MonsterInstance mob = new L2MonsterInstance(template1);
L2Spawn spawn = new L2Spawn(template1);
spawn.setLocx(target.getX() + 50);
spawn.setLocy(target.getY() + 50);
spawn.setLocz(target.getZ());
spawn.setAmount(1);
spawn.setHeading(target.getHeading());
spawn.setRespawnDelay(1);
SpawnTable.getInstance().addNewSpawn(spawn, false);
spawn.init();
spawn.getLastSpawn().setCurrentHp(999999999);
spawn.getLastSpawn().setName("event inscriptor");
spawn.getLastSpawn().setTitle(L2Event.eventName);
spawn.getLastSpawn().isEventMob = true;
spawn.getLastSpawn().isAggressive();
spawn.getLastSpawn().decayMe();
spawn.getLastSpawn().spawnMe(spawn.getLastSpawn().getX(), spawn.getLastSpawn().getY(), spawn.getLastSpawn().getZ());
spawn.getLastSpawn().broadcastPacket(new MagicSkillUse(spawn.getLastSpawn(), spawn.getLastSpawn(), 1034, 1, 1, 1));
npcs.add(String.valueOf(spawn.getLastSpawn().getObjectId()));
}
catch (Exception e)
{
_log.log(Level.WARNING, "Exception on spawn(): " + e.getMessage(), e);
}
}
public static void announceAllPlayers(String text)
{
Broadcast.announceToOnlinePlayers(text);
}
public static boolean isOnEvent(L2PcInstance player)
{
for (int k = 0; k < L2Event.teamsNumber; k++)
{
Iterator<String> it = L2Event.players.get(k + 1).iterator();
boolean temp = false;
while (it.hasNext())
{
temp = player.getName().equalsIgnoreCase(it.next());
if (temp)
{
return true;
}
}
}
return false;
}
public static void inscribePlayer(L2PcInstance player)
{
try
{
L2Event.participatingPlayers.add(player.getName());
player.eventkarma = player.getKarma();
player.eventX = player.getX();
player.eventY = player.getY();
player.eventZ = player.getZ();
player.eventpkkills = player.getPkKills();
player.eventpvpkills = player.getPvpKills();
player.eventTitle = player.getTitle();
player.kills.clear();
player.atEvent = true;
}
catch (Exception e)
{
_log.log(Level.WARNING, "Error when signing in the event:" + e.getMessage(), e);
}
}
public static void restoreChar(L2PcInstance player)
{
try
{
player.eventX = connectionLossData.get(player.getName()).eventX;
player.eventY = connectionLossData.get(player.getName()).eventY;
player.eventZ = connectionLossData.get(player.getName()).eventZ;
player.eventkarma = connectionLossData.get(player.getName()).eventKarma;
player.eventpvpkills = connectionLossData.get(player.getName()).eventPvpKills;
player.eventpkkills = connectionLossData.get(player.getName()).eventPkKills;
player.eventTitle = connectionLossData.get(player.getName()).eventTitle;
player.kills = connectionLossData.get(player.getName()).kills;
player.eventSitForced = connectionLossData.get(player.getName()).eventSitForced;
player.atEvent = true;
}
catch (Exception e)
{
}
}
public static void restoreAndTeleChar(L2PcInstance target)
{
try
{
restoreChar(target);
target.setTitle(target.eventTitle);
target.setKarma(target.eventkarma);
target.setPvpKills(target.eventpvpkills);
target.setPkKills(target.eventpkkills);
target.teleToLocation(target.eventX, target.eventY, target.eventZ, true);
target.kills.clear();
target.eventSitForced = false;
target.atEvent = false;
}
catch (Exception e)
{
}
}
}
@@ -0,0 +1,363 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ScheduledFuture;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.datatables.CharNameTable;
import com.l2jserver.gameserver.idfactory.IdFactory;
import com.l2jserver.gameserver.instancemanager.MailManager;
import com.l2jserver.gameserver.model.itemcontainer.Mail;
import com.l2jserver.util.Rnd;
/**
* @author Migi, DS
*/
public class Message
{
private static final int EXPIRATION = 360; // 15 days
private static final int COD_EXPIRATION = 12; // 12 hours
private static final int UNLOAD_ATTACHMENTS_INTERVAL = 900000; // 15-30 mins
// post state
public static final int DELETED = 0;
public static final int READED = 1;
public static final int REJECTED = 2;
private final int _messageId, _senderId, _receiverId;
private final long _expiration;
private String _senderName = null;
private String _receiverName = null;
private final String _subject, _content;
private boolean _unread, _fourStars, _news;
private boolean _deletedBySender;
private boolean _deletedByReceiver;
private final long _reqAdena;
private boolean _hasAttachments;
private Mail _attachments = null;
private ScheduledFuture<?> _unloadTask = null;
/*
* Constructor for restoring from DB.
*/
public Message(ResultSet rset) throws SQLException
{
_messageId = rset.getInt("messageId");
_senderId = rset.getInt("senderId");
_receiverId = rset.getInt("receiverId");
_subject = rset.getString("subject");
_content = rset.getString("content");
_expiration = rset.getLong("expiration");
_reqAdena = rset.getLong("reqAdena");
_hasAttachments = rset.getBoolean("hasAttachments");
_unread = rset.getBoolean("isUnread");
_deletedBySender = rset.getBoolean("isDeletedBySender");
_deletedByReceiver = rset.getBoolean("isDeletedByReceiver");
_fourStars = rset.getBoolean("isFourStars");
_news = rset.getBoolean("isNews");
}
/*
* This constructor used for creating new message.
*/
public Message(int senderId, int receiverId, boolean isCod, String subject, String text, long reqAdena)
{
_messageId = IdFactory.getInstance().getNextId();
_senderId = senderId;
_receiverId = receiverId;
_subject = subject;
_content = text;
_expiration = (isCod ? System.currentTimeMillis() + (COD_EXPIRATION * 3600000) : System.currentTimeMillis() + (EXPIRATION * 3600000));
_hasAttachments = false;
_unread = true;
_deletedBySender = false;
_deletedByReceiver = false;
_reqAdena = reqAdena;
}
/*
* This constructor used for auto-generation of the "return attachments" message
*/
public Message(Message msg)
{
_messageId = IdFactory.getInstance().getNextId();
_senderId = msg.getSenderId();
_receiverId = msg.getSenderId();
_subject = "";
_content = "";
_expiration = System.currentTimeMillis() + (EXPIRATION * 3600000);
_unread = true;
_deletedBySender = true;
_deletedByReceiver = false;
_fourStars = true;
_reqAdena = 0;
_hasAttachments = true;
_attachments = msg.getAttachments();
msg.removeAttachments();
_attachments.setNewMessageId(_messageId);
_unloadTask = ThreadPoolManager.getInstance().scheduleGeneral(new AttachmentsUnloadTask(this), UNLOAD_ATTACHMENTS_INTERVAL + Rnd.get(UNLOAD_ATTACHMENTS_INTERVAL));
}
public static final PreparedStatement getStatement(Message msg, Connection con) throws SQLException
{
PreparedStatement stmt = con.prepareStatement("INSERT INTO messages (messageId, senderId, receiverId, subject, content, expiration, reqAdena, hasAttachments, isUnread, isDeletedBySender, isDeletedByReceiver, isFourStars, isNews) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setInt(1, msg._messageId);
stmt.setInt(2, msg._senderId);
stmt.setInt(3, msg._receiverId);
stmt.setString(4, msg._subject);
stmt.setString(5, msg._content);
stmt.setLong(6, msg._expiration);
stmt.setLong(7, msg._reqAdena);
stmt.setString(8, String.valueOf(msg._hasAttachments));
stmt.setString(9, String.valueOf(msg._unread));
stmt.setString(10, String.valueOf(msg._deletedBySender));
stmt.setString(11, String.valueOf(msg._deletedByReceiver));
stmt.setString(12, String.valueOf(msg._fourStars));
stmt.setString(13, String.valueOf(msg._news));
return stmt;
}
public final int getId()
{
return _messageId;
}
public final int getSenderId()
{
return _senderId;
}
public final int getReceiverId()
{
return _receiverId;
}
public final String getSenderName()
{
if (_senderName == null)
{
if (_fourStars)
{
return "****";
}
_senderName = CharNameTable.getInstance().getNameById(_senderId);
if (_senderName == null)
{
_senderName = "";
}
}
return _senderName;
}
public final String getReceiverName()
{
if (_receiverName == null)
{
_receiverName = CharNameTable.getInstance().getNameById(_receiverId);
if (_receiverName == null)
{
_receiverName = "";
}
}
return _receiverName;
}
public final String getSubject()
{
return _subject;
}
public final String getContent()
{
return _content;
}
public final boolean isLocked()
{
return _reqAdena > 0;
}
public final long getExpiration()
{
return _expiration;
}
public final int getExpirationSeconds()
{
return (int) (_expiration / 1000);
}
public final boolean isUnread()
{
return _unread;
}
public final void markAsRead()
{
if (_unread)
{
_unread = false;
MailManager.getInstance().markAsReadInDb(_messageId);
}
}
public final boolean isDeletedBySender()
{
return _deletedBySender;
}
public final void setDeletedBySender()
{
if (!_deletedBySender)
{
_deletedBySender = true;
if (_deletedByReceiver)
{
MailManager.getInstance().deleteMessageInDb(_messageId);
}
else
{
MailManager.getInstance().markAsDeletedBySenderInDb(_messageId);
}
}
}
public final boolean isDeletedByReceiver()
{
return _deletedByReceiver;
}
public final void setDeletedByReceiver()
{
if (!_deletedByReceiver)
{
_deletedByReceiver = true;
if (_deletedBySender)
{
MailManager.getInstance().deleteMessageInDb(_messageId);
}
else
{
MailManager.getInstance().markAsDeletedByReceiverInDb(_messageId);
}
}
}
public final boolean isFourStars()
{
return _fourStars;
}
public final boolean isNews()
{
return _news;
}
public final void setIsNews(boolean val)
{
_news = val;
}
public final long getReqAdena()
{
return _reqAdena;
}
public final synchronized Mail getAttachments()
{
if (!_hasAttachments)
{
return null;
}
if (_attachments == null)
{
_attachments = new Mail(_senderId, _messageId);
_attachments.restore();
_unloadTask = ThreadPoolManager.getInstance().scheduleGeneral(new AttachmentsUnloadTask(this), UNLOAD_ATTACHMENTS_INTERVAL + Rnd.get(UNLOAD_ATTACHMENTS_INTERVAL));
}
return _attachments;
}
public final boolean hasAttachments()
{
return _hasAttachments;
}
public final synchronized void removeAttachments()
{
if (_attachments != null)
{
_attachments = null;
_hasAttachments = false;
MailManager.getInstance().removeAttachmentsInDb(_messageId);
if (_unloadTask != null)
{
_unloadTask.cancel(false);
}
}
}
public final synchronized Mail createAttachments()
{
if (_hasAttachments || (_attachments != null))
{
return null;
}
_attachments = new Mail(_senderId, _messageId);
_hasAttachments = true;
_unloadTask = ThreadPoolManager.getInstance().scheduleGeneral(new AttachmentsUnloadTask(this), UNLOAD_ATTACHMENTS_INTERVAL + Rnd.get(UNLOAD_ATTACHMENTS_INTERVAL));
return _attachments;
}
protected final synchronized void unloadAttachments()
{
if (_attachments != null)
{
_attachments.deleteMe();
_attachments = null;
}
}
static class AttachmentsUnloadTask implements Runnable
{
private Message _msg;
AttachmentsUnloadTask(Message msg)
{
_msg = msg;
}
@Override
public void run()
{
if (_msg != null)
{
_msg.unloadAttachments();
_msg = null;
}
}
}
}
@@ -0,0 +1,170 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
/**
* @author Gnacik
*/
public final class RecoBonus
{
private static final int[][] _recoBonus =
{
{
25,
50,
50,
50,
50,
50,
50,
50,
50,
50
},
{
16,
33,
50,
50,
50,
50,
50,
50,
50,
50
},
{
12,
25,
37,
50,
50,
50,
50,
50,
50,
50
},
{
10,
20,
30,
40,
50,
50,
50,
50,
50,
50
},
{
8,
16,
25,
33,
41,
50,
50,
50,
50,
50
},
{
7,
14,
21,
28,
35,
42,
50,
50,
50,
50
},
{
6,
12,
18,
25,
31,
37,
43,
50,
50,
50
},
{
5,
11,
16,
22,
27,
33,
38,
44,
50,
50
},
{
5,
10,
15,
20,
25,
30,
35,
40,
45,
50
}
};
public static int getRecoBonus(L2PcInstance activeChar)
{
if ((activeChar != null) && activeChar.isOnline())
{
if (activeChar.getRecomHave() == 0)
{
return 0;
}
int _lvl = (int) Math.ceil(activeChar.getLevel() / 10);
int _exp = (int) Math.ceil((Math.min(100, activeChar.getRecomHave()) - 1) / 10);
return _recoBonus[_lvl][_exp];
}
return 0;
}
public static double getRecoMultiplier(L2PcInstance activeChar)
{
double _multiplier = 1;
int bonus = getRecoBonus(activeChar);
if (bonus > 0)
{
_multiplier = (1 + (bonus / 100));
}
if (_multiplier < 1)
{
_multiplier = 1;
}
return _multiplier;
}
}
@@ -0,0 +1,61 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.util.Calendar;
import java.util.List;
import com.l2jserver.gameserver.model.L2Clan;
import com.l2jserver.gameserver.model.L2SiegeClan;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
/**
* @author JIV
*/
public interface Siegable
{
public void startSiege();
public void endSiege();
public L2SiegeClan getAttackerClan(int clanId);
public L2SiegeClan getAttackerClan(L2Clan clan);
public List<L2SiegeClan> getAttackerClans();
public List<L2PcInstance> getAttackersInZone();
public boolean checkIsAttacker(L2Clan clan);
public L2SiegeClan getDefenderClan(int clanId);
public L2SiegeClan getDefenderClan(L2Clan clan);
public List<L2SiegeClan> getDefenderClans();
public boolean checkIsDefender(L2Clan clan);
public List<L2Npc> getFlag(L2Clan clan);
public Calendar getSiegeDate();
public boolean giveFame();
public int getFameFrequency();
public int getFameAmount();
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,183 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.util.Map;
import javolution.util.FastMap;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
/**
* @author FBIagent
*/
public class TvTEventTeam
{
/** The name of the team<br> */
private final String _name;
/** The team spot coordinated<br> */
private int[] _coordinates = new int[3];
/** The points of the team<br> */
private short _points;
/** Name and instance of all participated players in FastMap<br> */
private Map<Integer, L2PcInstance> _participatedPlayers = new FastMap<>();
/**
* C'tor initialize the team<br>
* <br>
* @param name as String<br>
* @param coordinates as int[]<br>
*/
public TvTEventTeam(String name, int[] coordinates)
{
_name = name;
_coordinates = coordinates;
_points = 0;
}
/**
* Adds a player to the team<br>
* <br>
* @param playerInstance as L2PcInstance<br>
* @return boolean: true if success, otherwise false<br>
*/
public boolean addPlayer(L2PcInstance playerInstance)
{
if (playerInstance == null)
{
return false;
}
synchronized (_participatedPlayers)
{
_participatedPlayers.put(playerInstance.getObjectId(), playerInstance);
}
return true;
}
/**
* Removes a player from the team<br>
* <br>
* @param playerName as String<br>
*/
public void removePlayer(int playerObjectId)
{
synchronized (_participatedPlayers)
{
_participatedPlayers.remove(playerObjectId);
}
}
/**
* Increases the points of the team<br>
*/
public void increasePoints()
{
++_points;
}
/**
* Cleanup the team and make it ready for adding players again<br>
*/
public void cleanMe()
{
_participatedPlayers.clear();
_participatedPlayers = new FastMap<>();
_points = 0;
}
/**
* Is given player in this team?<br>
* <br>
* @param playerName as String<br>
* @return boolean: true if player is in this team, otherwise false<br>
*/
public boolean containsPlayer(int playerObjectId)
{
boolean containsPlayer;
synchronized (_participatedPlayers)
{
containsPlayer = _participatedPlayers.containsKey(playerObjectId);
}
return containsPlayer;
}
/**
* Returns the name of the team<br>
* <br>
* @return String: name of the team<br>
*/
public String getName()
{
return _name;
}
/**
* Returns the coordinates of the team spot<br>
* <br>
* @return int[]: team coordinates<br>
*/
public int[] getCoordinates()
{
return _coordinates;
}
/**
* Returns the points of the team<br>
* <br>
* @return short: team points<br>
*/
public short getPoints()
{
return _points;
}
/**
* Returns name and instance of all participated players in FastMap<br>
* <br>
* @return Map<String, L2PcInstance>: map of players in this team<br>
*/
public Map<Integer, L2PcInstance> getParticipatedPlayers()
{
Map<Integer, L2PcInstance> participatedPlayers = null;
synchronized (_participatedPlayers)
{
participatedPlayers = _participatedPlayers;
}
return participatedPlayers;
}
/**
* Returns player count of this team<br>
* <br>
* @return int: number of players in team<br>
*/
public int getParticipatedPlayerCount()
{
int participatedPlayerCount;
synchronized (_participatedPlayers)
{
participatedPlayerCount = _participatedPlayers.size();
}
return participatedPlayerCount;
}
}
@@ -0,0 +1,123 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import com.l2jserver.Config;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.model.actor.L2Summon;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.util.Rnd;
public class TvTEventTeleporter implements Runnable
{
/** The instance of the player to teleport */
private L2PcInstance _playerInstance = null;
/** Coordinates of the spot to teleport to */
private int[] _coordinates = new int[3];
/** Admin removed this player from event */
private boolean _adminRemove = false;
/**
* Initialize the teleporter and start the delayed task<br>
* <br>
* @param playerInstance as L2PcInstance<br>
* @param coordinates as int[]<br>
* @param fastShedule as boolean<br>
* @param adminRemove as boolean<br>
*/
public TvTEventTeleporter(L2PcInstance playerInstance, int[] coordinates, boolean fastSchedule, boolean adminRemove)
{
_playerInstance = playerInstance;
_coordinates = coordinates;
_adminRemove = adminRemove;
long delay = (TvTEvent.isStarted() ? Config.TVT_EVENT_RESPAWN_TELEPORT_DELAY : Config.TVT_EVENT_START_LEAVE_TELEPORT_DELAY) * 1000;
ThreadPoolManager.getInstance().scheduleGeneral(this, fastSchedule ? 0 : delay);
}
/**
* The task method to teleport the player<br>
* 1. Unsummon pet if there is one<br>
* 2. Remove all effects<br>
* 3. Revive and full heal the player<br>
* 4. Teleport the player<br>
* 5. Broadcast status and user info<br>
* <br>
* @see java.lang.Runnable#run()<br>
*/
@Override
public void run()
{
if (_playerInstance == null)
{
return;
}
L2Summon summon = _playerInstance.getPet();
if (summon != null)
{
summon.unSummon(_playerInstance);
}
if ((Config.TVT_EVENT_EFFECTS_REMOVAL == 0) || ((Config.TVT_EVENT_EFFECTS_REMOVAL == 1) && ((_playerInstance.getTeam() == 0) || (_playerInstance.isInDuel() && (_playerInstance.getDuelState() != Duel.DUELSTATE_INTERRUPTED)))))
{
_playerInstance.stopAllEffectsExceptThoseThatLastThroughDeath();
}
if (_playerInstance.isInDuel())
{
_playerInstance.setDuelState(Duel.DUELSTATE_INTERRUPTED);
}
int TvTInstance = TvTEvent.getTvTEventInstance();
if (TvTInstance != 0)
{
if (TvTEvent.isStarted() && !_adminRemove)
{
_playerInstance.setInstanceId(TvTInstance);
}
else
{
_playerInstance.setInstanceId(0);
}
}
else
{
_playerInstance.setInstanceId(0);
}
_playerInstance.doRevive();
_playerInstance.teleToLocation((_coordinates[0] + Rnd.get(101)) - 50, (_coordinates[1] + Rnd.get(101)) - 50, _coordinates[2], false);
if (TvTEvent.isStarted() && !_adminRemove)
{
_playerInstance.setTeam(TvTEvent.getParticipantTeamId(_playerInstance.getObjectId()) + 1);
}
else
{
_playerInstance.setTeam(0);
}
_playerInstance.setCurrentCp(_playerInstance.getMaxCp());
_playerInstance.setCurrentHp(_playerInstance.getMaxHp());
_playerInstance.setCurrentMp(_playerInstance.getMaxMp());
_playerInstance.broadcastStatusUpdate();
_playerInstance.broadcastUserInfo();
}
}
@@ -0,0 +1,294 @@
/*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.entity;
import java.util.Calendar;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Logger;
import com.l2jserver.Config;
import com.l2jserver.gameserver.Announcements;
import com.l2jserver.gameserver.ThreadPoolManager;
/**
* @author FBIagent
*/
public class TvTManager
{
protected static final Logger _log = Logger.getLogger(TvTManager.class.getName());
/** Task for event cycles<br> */
private TvTStartTask _task;
/**
* New instance only by getInstance()<br>
*/
private TvTManager()
{
if (Config.TVT_EVENT_ENABLED)
{
TvTEvent.init();
scheduleEventStart();
_log.info("TvTEventEngine[TvTManager.TvTManager()]: Started.");
}
else
{
_log.info("TvTEventEngine[TvTManager.TvTManager()]: Engine is disabled.");
}
}
/**
* Initialize new/Returns the one and only instance<br>
* <br>
* @return TvTManager<br>
*/
public static TvTManager getInstance()
{
return SingletonHolder._instance;
}
/**
* Starts TvTStartTask
*/
public void scheduleEventStart()
{
try
{
Calendar currentTime = Calendar.getInstance();
Calendar nextStartTime = null;
Calendar testStartTime = null;
for (String timeOfDay : Config.TVT_EVENT_INTERVAL)
{
// Creating a Calendar object from the specified interval value
testStartTime = Calendar.getInstance();
testStartTime.setLenient(true);
String[] splitTimeOfDay = timeOfDay.split(":");
testStartTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(splitTimeOfDay[0]));
testStartTime.set(Calendar.MINUTE, Integer.parseInt(splitTimeOfDay[1]));
// If the date is in the past, make it the next day (Example: Checking for "1:00", when the time is 23:57.)
if (testStartTime.getTimeInMillis() < currentTime.getTimeInMillis())
{
testStartTime.add(Calendar.DAY_OF_MONTH, 1);
}
// Check for the test date to be the minimum (smallest in the specified list)
if ((nextStartTime == null) || (testStartTime.getTimeInMillis() < nextStartTime.getTimeInMillis()))
{
nextStartTime = testStartTime;
}
}
_task = new TvTStartTask(nextStartTime.getTimeInMillis());
ThreadPoolManager.getInstance().executeTask(_task);
}
catch (Exception e)
{
_log.warning("TvTEventEngine[TvTManager.scheduleEventStart()]: Error figuring out a start time. Check TvTEventInterval in config file.");
}
}
/**
* Method to start participation
*/
public void startReg()
{
if (!TvTEvent.startParticipation())
{
Announcements.getInstance().announceToAll("TvT Event: Event was cancelled.");
_log.warning("TvTEventEngine[TvTManager.run()]: Error spawning event npc for participation.");
scheduleEventStart();
}
else
{
Announcements.getInstance().announceToAll("TvT Event: Registration opened for " + Config.TVT_EVENT_PARTICIPATION_TIME + " minute(s).");
// schedule registration end
_task.setStartTime(System.currentTimeMillis() + (60000L * Config.TVT_EVENT_PARTICIPATION_TIME));
ThreadPoolManager.getInstance().executeTask(_task);
}
}
/**
* Method to start the fight
*/
public void startEvent()
{
if (!TvTEvent.startFight())
{
Announcements.getInstance().announceToAll("TvT Event: Event cancelled due to lack of Participation.");
_log.info("TvTEventEngine[TvTManager.run()]: Lack of registration, abort event.");
scheduleEventStart();
}
else
{
TvTEvent.sysMsgToAllParticipants("TvT Event: Teleporting participants to an arena in " + Config.TVT_EVENT_START_LEAVE_TELEPORT_DELAY + " second(s).");
_task.setStartTime(System.currentTimeMillis() + (60000L * Config.TVT_EVENT_RUNNING_TIME));
ThreadPoolManager.getInstance().executeTask(_task);
}
}
/**
* Method to end the event and reward
*/
public void endEvent()
{
Announcements.getInstance().announceToAll(TvTEvent.calculateRewards());
TvTEvent.sysMsgToAllParticipants("TvT Event: Teleporting back to the registration npc in " + Config.TVT_EVENT_START_LEAVE_TELEPORT_DELAY + " second(s).");
TvTEvent.stopFight();
scheduleEventStart();
}
public void skipDelay()
{
if (_task.nextRun.cancel(false))
{
_task.setStartTime(System.currentTimeMillis());
ThreadPoolManager.getInstance().executeTask(_task);
}
}
/**
* Class for TvT cycles
*/
class TvTStartTask implements Runnable
{
private long _startTime;
public ScheduledFuture<?> nextRun;
public TvTStartTask(long startTime)
{
_startTime = startTime;
}
public void setStartTime(long startTime)
{
_startTime = startTime;
}
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run()
{
int delay = (int) Math.round((_startTime - System.currentTimeMillis()) / 1000.0);
if (delay > 0)
{
announce(delay);
}
int nextMsg = 0;
if (delay > 3600)
{
nextMsg = delay - 3600;
}
else if (delay > 1800)
{
nextMsg = delay - 1800;
}
else if (delay > 900)
{
nextMsg = delay - 900;
}
else if (delay > 600)
{
nextMsg = delay - 600;
}
else if (delay > 300)
{
nextMsg = delay - 300;
}
else if (delay > 60)
{
nextMsg = delay - 60;
}
else if (delay > 5)
{
nextMsg = delay - 5;
}
else if (delay > 0)
{
nextMsg = delay;
}
else
{
// start
if (TvTEvent.isInactive())
{
startReg();
}
else if (TvTEvent.isParticipating())
{
startEvent();
}
else
{
endEvent();
}
}
if (delay > 0)
{
nextRun = ThreadPoolManager.getInstance().scheduleGeneral(this, nextMsg * 1000);
}
}
private void announce(long time)
{
if ((time >= 3600) && ((time % 3600) == 0))
{
if (TvTEvent.isParticipating())
{
Announcements.getInstance().announceToAll("TvT Event: " + (time / 60 / 60) + " hour(s) until registration is closed!");
}
else if (TvTEvent.isStarted())
{
TvTEvent.sysMsgToAllParticipants("TvT Event: " + (time / 60 / 60) + " hour(s) until event is finished!");
}
}
else if (time >= 60)
{
if (TvTEvent.isParticipating())
{
Announcements.getInstance().announceToAll("TvT Event: " + (time / 60) + " minute(s) until registration is closed!");
}
else if (TvTEvent.isStarted())
{
TvTEvent.sysMsgToAllParticipants("TvT Event: " + (time / 60) + " minute(s) until the event is finished!");
}
}
else
{
if (TvTEvent.isParticipating())
{
Announcements.getInstance().announceToAll("TvT Event: " + time + " second(s) until registration is closed!");
}
else if (TvTEvent.isStarted())
{
TvTEvent.sysMsgToAllParticipants("TvT Event: " + time + " second(s) until the event is finished!");
}
}
}
}
@SuppressWarnings("synthetic-access")
private static class SingletonHolder
{
protected static final TvTManager _instance = new TvTManager();
}
}