Reformat before I go crazy.

This commit is contained in:
drtshock
2014-04-04 13:55:21 -05:00
parent 0c3ea377dd
commit 814e439705
124 changed files with 11302 additions and 13164 deletions

View File

@@ -1,393 +1,332 @@
package com.massivecraft.factions.integration;
import com.massivecraft.factions.*;
import com.massivecraft.factions.iface.EconomyParticipator;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.RelationUtil;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.P;
import com.massivecraft.factions.iface.EconomyParticipator;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.RelationUtil;
public class Econ {
private static Economy econ = null;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
public static void setup() {
if (isSetup()) return;
String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" ";
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
P.p.log(integrationFail + "is not installed.");
return;
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
P.p.log(integrationFail + "is not hooked into an economy plugin.");
return;
}
econ = rsp.getProvider();
P.p.log("Economy integration through Vault plugin successful.");
if (!Conf.econEnabled)
P.p.log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true");
P.p.cmdBase.cmdHelp.updateHelp();
oldMoneyDoTransfer();
}
public static boolean shouldBeUsed() {
return Conf.econEnabled && econ != null && econ.isEnabled();
}
public static boolean isSetup() {
return econ != null;
}
public class Econ
{
private static Economy econ = null;
public static void modifyUniverseMoney(double delta) {
if (!shouldBeUsed()) return;
public static void setup()
{
if (isSetup()) return;
if (Conf.econUniverseAccount == null) return;
if (Conf.econUniverseAccount.length() == 0) return;
if (!econ.hasAccount(Conf.econUniverseAccount)) return;
String integrationFail = "Economy integration is "+(Conf.econEnabled ? "enabled, but" : "disabled, and")+" the plugin \"Vault\" ";
modifyBalance(Conf.econUniverseAccount, delta);
}
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null)
{
P.p.log(integrationFail+"is not installed.");
return;
}
public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) {
if (!shouldBeUsed()) {
P.p.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin.");
return;
}
to.msg("<a>%s's<i> balance is <h>%s<i>.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId())));
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null)
{
P.p.log(integrationFail+"is not hooked into an economy plugin.");
return;
}
econ = rsp.getProvider();
public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you) {
Faction fI = RelationUtil.getFaction(i);
Faction fYou = RelationUtil.getFaction(you);
P.p.log("Economy integration through Vault plugin successful.");
// This is a system invoker. Accept it.
if (fI == null) return true;
if ( ! Conf.econEnabled)
P.p.log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true");
// Bypassing players can do any kind of transaction
if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) return true;
P.p.cmdBase.cmdHelp.updateHelp();
// Players with the any withdraw can do.
if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) return true;
oldMoneyDoTransfer();
}
// You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again.
if (i == you) return true;
public static boolean shouldBeUsed()
{
return Conf.econEnabled && econ != null && econ.isEnabled();
}
public static boolean isSetup()
{
return econ != null;
}
// A faction can always transfer away the money of it's members and its own money...
// This will however probably never happen as a faction does not have free will.
// Ohh by the way... Yes it could. For daily rent to the faction.
if (i == fI && fI == fYou) return true;
// Factions can be controlled by members that are moderators... or any member if any member can withdraw.
if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer) i).getRole().value >= Role.MODERATOR.value))
return true;
public static void modifyUniverseMoney(double delta)
{
if (!shouldBeUsed()) return;
// Otherwise you may not! ;,,;
i.msg("<h>%s<i> lacks permission to control <h>%s's<i> money.", i.describeTo(i, true), you.describeTo(i));
return false;
}
if (Conf.econUniverseAccount == null) return;
if (Conf.econUniverseAccount.length() == 0) return;
if ( ! econ.hasAccount(Conf.econUniverseAccount)) return;
public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) {
return transferMoney(invoker, from, to, amount, true);
}
modifyBalance(Conf.econUniverseAccount, delta);
}
public static void sendBalanceInfo(FPlayer to, EconomyParticipator about)
{
if (!shouldBeUsed())
{
P.p.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin.");
return;
}
to.msg("<a>%s's<i> balance is <h>%s<i>.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId())));
}
public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you)
{
Faction fI = RelationUtil.getFaction(i);
Faction fYou = RelationUtil.getFaction(you);
// This is a system invoker. Accept it.
if (fI == null) return true;
// Bypassing players can do any kind of transaction
if (i instanceof FPlayer && ((FPlayer)i).isAdminBypassing()) return true;
// Players with the any withdraw can do.
if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer)i).getPlayer())) return true;
// You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again.
if (i == you) return true;
// A faction can always transfer away the money of it's members and its own money...
// This will however probably never happen as a faction does not have free will.
// Ohh by the way... Yes it could. For daily rent to the faction.
if (i == fI && fI == fYou) return true;
// Factions can be controlled by members that are moderators... or any member if any member can withdraw.
if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer)i).getRole().value >= Role.MODERATOR.value)) return true;
// Otherwise you may not! ;,,;
i.msg("<h>%s<i> lacks permission to control <h>%s's<i> money.", i.describeTo(i, true), you.describeTo(i));
return false;
}
public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount)
{
return transferMoney(invoker, from, to, amount, true);
}
public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify)
{
if ( ! shouldBeUsed()) return false;
public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) {
if (!shouldBeUsed()) return false;
// The amount must be positive.
// If the amount is negative we must flip and multiply amount with -1.
if (amount < 0)
{
amount *= -1;
EconomyParticipator temp = from;
from = to;
to = temp;
}
// Check the rights
if ( ! canIControllYou(invoker, from)) return false;
// Is there enough money for the transaction to happen?
if ( ! econ.has(from.getAccountId(), amount))
{
// There was not enough money to pay
if (invoker != null && notify)
invoker.msg("<h>%s<b> can't afford to transfer <h>%s<b> to %s<b>.", from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker));
// The amount must be positive.
// If the amount is negative we must flip and multiply amount with -1.
if (amount < 0) {
amount *= -1;
EconomyParticipator temp = from;
from = to;
to = temp;
}
return false;
}
// Transfer money
EconomyResponse erw = econ.withdrawPlayer(from.getAccountId(), amount);
// Check the rights
if (!canIControllYou(invoker, from)) return false;
if (erw.transactionSuccess()) {
EconomyResponse erd = econ.depositPlayer(to.getAccountId(), amount);
if (erd.transactionSuccess()) {
if (notify) sendTransferInfo(invoker, from, to, amount);
return true;
} else {
// transaction failed, refund account
econ.depositPlayer(from.getAccountId(), amount);
}
}
// Is there enough money for the transaction to happen?
if (!econ.has(from.getAccountId(), amount)) {
// There was not enough money to pay
if (invoker != null && notify)
invoker.msg("<h>%s<b> can't afford to transfer <h>%s<b> to %s<b>.", from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker));
// if we get here something with the transaction failed
if (notify)
invoker.msg("Unable to transfer %s<b> to <h>%s<b> from <h>%s<b>.", moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true));
return false;
}
return false;
}
public static Set<FPlayer> getFplayers(EconomyParticipator ep)
{
Set<FPlayer> fplayers = new HashSet<FPlayer>();
if (ep == null)
{
// Add nothing
}
else if (ep instanceof FPlayer)
{
fplayers.add((FPlayer)ep);
}
else if (ep instanceof Faction)
{
fplayers.addAll(((Faction)ep).getFPlayers());
}
return fplayers;
}
public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount)
{
Set<FPlayer> recipients = new HashSet<FPlayer>();
recipients.addAll(getFplayers(invoker));
recipients.addAll(getFplayers(from));
recipients.addAll(getFplayers(to));
if (invoker == null)
{
for (FPlayer recipient : recipients)
{
recipient.msg("<h>%s<i> was transfered from <h>%s<i> to <h>%s<i>.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient));
}
}
else if (invoker == from)
{
for (FPlayer recipient : recipients)
{
recipient.msg("<h>%s<i> <h>gave %s<i> to <h>%s<i>.", from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient));
}
}
else if (invoker == to)
{
for (FPlayer recipient : recipients)
{
recipient.msg("<h>%s<i> <h>took %s<i> from <h>%s<i>.", to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient));
}
}
else
{
for (FPlayer recipient : recipients)
{
recipient.msg("<h>%s<i> transfered <h>%s<i> from <h>%s<i> to <h>%s<i>.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient));
}
}
}
// Transfer money
EconomyResponse erw = econ.withdrawPlayer(from.getAccountId(), amount);
public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis)
{
if ( ! shouldBeUsed()) return true;
if (erw.transactionSuccess()) {
EconomyResponse erd = econ.depositPlayer(to.getAccountId(), amount);
if (erd.transactionSuccess()) {
if (notify) sendTransferInfo(invoker, from, to, amount);
return true;
} else {
// transaction failed, refund account
econ.depositPlayer(from.getAccountId(), amount);
}
}
if ( ! econ.has(ep.getAccountId(), delta))
{
if (toDoThis != null && !toDoThis.isEmpty())
ep.msg("<h>%s<i> can't afford <h>%s<i> %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis);
return false;
}
return true;
}
// if we get here something with the transaction failed
if (notify)
invoker.msg("Unable to transfer %s<b> to <h>%s<b> from <h>%s<b>.", moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true));
public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis)
{
if ( ! shouldBeUsed()) return false;
return false;
}
String acc = ep.getAccountId();
String You = ep.describeTo(ep, true);
if (delta == 0)
{
// no money actually transferred?
public static Set<FPlayer> getFplayers(EconomyParticipator ep) {
Set<FPlayer> fplayers = new HashSet<FPlayer>();
if (ep == null) {
// Add nothing
} else if (ep instanceof FPlayer) {
fplayers.add((FPlayer) ep);
} else if (ep instanceof Faction) {
fplayers.addAll(((Faction) ep).getFPlayers());
}
return fplayers;
}
public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) {
Set<FPlayer> recipients = new HashSet<FPlayer>();
recipients.addAll(getFplayers(invoker));
recipients.addAll(getFplayers(from));
recipients.addAll(getFplayers(to));
if (invoker == null) {
for (FPlayer recipient : recipients) {
recipient.msg("<h>%s<i> was transfered from <h>%s<i> to <h>%s<i>.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient));
}
} else if (invoker == from) {
for (FPlayer recipient : recipients) {
recipient.msg("<h>%s<i> <h>gave %s<i> to <h>%s<i>.", from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient));
}
} else if (invoker == to) {
for (FPlayer recipient : recipients) {
recipient.msg("<h>%s<i> <h>took %s<i> from <h>%s<i>.", to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient));
}
} else {
for (FPlayer recipient : recipients) {
recipient.msg("<h>%s<i> transfered <h>%s<i> from <h>%s<i> to <h>%s<i>.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient));
}
}
}
public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) {
if (!shouldBeUsed()) return true;
if (!econ.has(ep.getAccountId(), delta)) {
if (toDoThis != null && !toDoThis.isEmpty())
ep.msg("<h>%s<i> can't afford <h>%s<i> %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis);
return false;
}
return true;
}
public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) {
if (!shouldBeUsed()) return false;
String acc = ep.getAccountId();
String You = ep.describeTo(ep, true);
if (delta == 0) {
// no money actually transferred?
// ep.msg("<h>%s<i> didn't have to pay anything %s.", You, forDoingThis); // might be for gains, might be for losses
return true;
}
return true;
}
if (delta > 0)
{
// The player should gain money
// The account might not have enough space
EconomyResponse er = econ.depositPlayer(acc, delta);
if (er.transactionSuccess()) {
modifyUniverseMoney(-delta);
if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg("<h>%s<i> gained <h>%s<i> %s.", You, moneyString(delta), forDoingThis);
return true;
} else {
// transfer to account failed
if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg("<h>%s<i> would have gained <h>%s<i> %s, but the deposit failed.", You, moneyString(delta), forDoingThis);
return false;
}
}
else
{
// The player should loose money
// The player might not have enough.
if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess())
{
// There is enough money to pay
modifyUniverseMoney(-delta);
if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg("<h>%s<i> lost <h>%s<i> %s.", You, moneyString(-delta), forDoingThis);
return true;
}
else
{
// There was not enough money to pay
if (toDoThis != null && !toDoThis.isEmpty())
ep.msg("<h>%s<i> can't afford <h>%s<i> %s.", You, moneyString(-delta), toDoThis);
return false;
}
}
}
if (delta > 0) {
// The player should gain money
// The account might not have enough space
EconomyResponse er = econ.depositPlayer(acc, delta);
if (er.transactionSuccess()) {
modifyUniverseMoney(-delta);
if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg("<h>%s<i> gained <h>%s<i> %s.", You, moneyString(delta), forDoingThis);
return true;
} else {
// transfer to account failed
if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg("<h>%s<i> would have gained <h>%s<i> %s, but the deposit failed.", You, moneyString(delta), forDoingThis);
return false;
}
} else {
// The player should loose money
// The player might not have enough.
// format money string based on server's set currency type, like "24 gold" or "$24.50"
public static String moneyString(double amount)
{
return econ.format(amount);
}
public static void oldMoneyDoTransfer()
{
if ( ! shouldBeUsed()) return;
for (Faction faction : Factions.i.get())
{
if (faction.money > 0)
{
econ.depositPlayer(faction.getAccountId(), faction.money);
faction.money = 0;
}
}
}
if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) {
// There is enough money to pay
modifyUniverseMoney(-delta);
if (forDoingThis != null && !forDoingThis.isEmpty())
ep.msg("<h>%s<i> lost <h>%s<i> %s.", You, moneyString(-delta), forDoingThis);
return true;
} else {
// There was not enough money to pay
if (toDoThis != null && !toDoThis.isEmpty())
ep.msg("<h>%s<i> can't afford <h>%s<i> %s.", You, moneyString(-delta), toDoThis);
return false;
}
}
}
// calculate the cost for claiming land
public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction)
{
if ( ! shouldBeUsed())
{
return 0d;
}
// format money string based on server's set currency type, like "24 gold" or "$24.50"
public static String moneyString(double amount) {
return econ.format(amount);
}
// basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction
return Conf.econCostClaimWilderness
+ (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand)
- (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus: 0);
}
public static void oldMoneyDoTransfer() {
if (!shouldBeUsed()) return;
// calculate refund amount for unclaiming land
public static double calculateClaimRefund(int ownedLand)
{
return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier;
}
for (Faction faction : Factions.i.get()) {
if (faction.money > 0) {
econ.depositPlayer(faction.getAccountId(), faction.money);
faction.money = 0;
}
}
}
// calculate value of all owned land
public static double calculateTotalLandValue(int ownedLand)
{
double amount = 0;
for (int x = 0; x < ownedLand; x++) {
amount += calculateClaimCost(x, false);
}
return amount;
}
// calculate the cost for claiming land
public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) {
if (!shouldBeUsed()) {
return 0d;
}
// calculate refund amount for all owned land
public static double calculateTotalLandRefund(int ownedLand)
{
return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier;
}
// basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction
return Conf.econCostClaimWilderness
+ (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand)
- (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus : 0);
}
// calculate refund amount for unclaiming land
public static double calculateClaimRefund(int ownedLand) {
return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier;
}
// calculate value of all owned land
public static double calculateTotalLandValue(int ownedLand) {
double amount = 0;
for (int x = 0; x < ownedLand; x++) {
amount += calculateClaimCost(x, false);
}
return amount;
}
// calculate refund amount for all owned land
public static double calculateTotalLandRefund(int ownedLand) {
return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier;
}
// -------------------------------------------- //
// Standard account management methods
// -------------------------------------------- //
// -------------------------------------------- //
// Standard account management methods
// -------------------------------------------- //
public static boolean hasAccount(String name)
{
return econ.hasAccount(name);
}
public static boolean hasAccount(String name) {
return econ.hasAccount(name);
}
public static double getBalance(String account)
{
return econ.getBalance(account);
}
public static double getBalance(String account) {
return econ.getBalance(account);
}
public static boolean setBalance(String account, double amount)
{
double current = econ.getBalance(account);
if (current > amount)
return econ.withdrawPlayer(account, current - amount).transactionSuccess();
else
return econ.depositPlayer(account, amount - current).transactionSuccess();
}
public static boolean setBalance(String account, double amount) {
double current = econ.getBalance(account);
if (current > amount)
return econ.withdrawPlayer(account, current - amount).transactionSuccess();
else
return econ.depositPlayer(account, amount - current).transactionSuccess();
}
public static boolean modifyBalance(String account, double amount)
{
if (amount < 0)
return econ.withdrawPlayer(account, -amount).transactionSuccess();
else
return econ.depositPlayer(account, amount).transactionSuccess();
}
public static boolean modifyBalance(String account, double amount) {
if (amount < 0)
return econ.withdrawPlayer(account, -amount).transactionSuccess();
else
return econ.depositPlayer(account, amount).transactionSuccess();
}
public static boolean deposit(String account, double amount)
{
return econ.depositPlayer(account, amount).transactionSuccess();
}
public static boolean deposit(String account, double amount) {
return econ.depositPlayer(account, amount).transactionSuccess();
}
public static boolean withdraw(String account, double amount)
{
return econ.withdrawPlayer(account, amount).transactionSuccess();
}
public static boolean withdraw(String account, double amount) {
return econ.withdrawPlayer(account, amount).transactionSuccess();
}
}

View File

@@ -1,22 +1,20 @@
package com.massivecraft.factions.integration;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.P;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.Teleport;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.chat.EssentialsChat;
import com.earth2me.essentials.chat.EssentialsLocalChatEvent;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.P;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
/*
@@ -26,111 +24,90 @@ import com.earth2me.essentials.chat.EssentialsLocalChatEvent;
// silence deprecation warnings with this old interface
@SuppressWarnings("deprecation")
public class EssentialsFeatures
{
private static EssentialsChat essChat;
private static IEssentials essentials;
public class EssentialsFeatures {
private static EssentialsChat essChat;
private static IEssentials essentials;
public static void setup()
{
// integrate main essentials plugin
// TODO: this is the old Essentials method not supported in 3.0... probably needs to eventually be moved to EssentialsOldVersionFeatures and new method implemented
if (essentials == null)
{
Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials");
if (ess != null && ess.isEnabled())
essentials = (IEssentials)ess;
}
public static void setup() {
// integrate main essentials plugin
// TODO: this is the old Essentials method not supported in 3.0... probably needs to eventually be moved to EssentialsOldVersionFeatures and new method implemented
if (essentials == null) {
Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials");
if (ess != null && ess.isEnabled())
essentials = (IEssentials) ess;
}
// integrate chat
if (essChat != null) return;
// integrate chat
if (essChat != null) return;
Plugin test = Bukkit.getServer().getPluginManager().getPlugin("EssentialsChat");
if (test == null || !test.isEnabled()) return;
Plugin test = Bukkit.getServer().getPluginManager().getPlugin("EssentialsChat");
if (test == null || !test.isEnabled()) return;
essChat = (EssentialsChat)test;
essChat = (EssentialsChat) test;
// try newer Essentials 3.x integration method
try
{
Class.forName("com.earth2me.essentials.chat.EssentialsLocalChatEvent");
integrateChat(essChat);
}
catch (ClassNotFoundException ex)
{
// no? try older Essentials 2.x integration method
try
{
EssentialsOldVersionFeatures.integrateChat(essChat);
}
catch (NoClassDefFoundError ex2) { /* no known integration method, then */ }
}
}
// try newer Essentials 3.x integration method
try {
Class.forName("com.earth2me.essentials.chat.EssentialsLocalChatEvent");
integrateChat(essChat);
} catch (ClassNotFoundException ex) {
// no? try older Essentials 2.x integration method
try {
EssentialsOldVersionFeatures.integrateChat(essChat);
} catch (NoClassDefFoundError ex2) { /* no known integration method, then */ }
}
}
public static void unhookChat()
{
if (essChat == null) return;
public static void unhookChat() {
if (essChat == null) return;
try
{
EssentialsOldVersionFeatures.unhookChat();
}
catch (NoClassDefFoundError ex) {}
}
try {
EssentialsOldVersionFeatures.unhookChat();
} catch (NoClassDefFoundError ex) {
}
}
// return false if feature is disabled or Essentials isn't available
public static boolean handleTeleport(Player player, Location loc)
{
if ( ! Conf.homesTeleportCommandEssentialsIntegration || essentials == null) return false;
// return false if feature is disabled or Essentials isn't available
public static boolean handleTeleport(Player player, Location loc) {
if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) return false;
Teleport teleport = (Teleport) essentials.getUser(player).getTeleport();
Trade trade = new Trade(Conf.econCostHome, essentials);
try
{
teleport.teleport(loc, trade);
}
catch (Exception e)
{
player.sendMessage(ChatColor.RED.toString()+e.getMessage());
}
return true;
}
Teleport teleport = (Teleport) essentials.getUser(player).getTeleport();
Trade trade = new Trade(Conf.econCostHome, essentials);
try {
teleport.teleport(loc, trade);
} catch (Exception e) {
player.sendMessage(ChatColor.RED.toString() + e.getMessage());
}
return true;
}
public static void integrateChat(EssentialsChat instance)
{
essChat = instance;
try
{
Bukkit.getServer().getPluginManager().registerEvents(new LocalChatListener(), P.p);
P.p.log("Found and will integrate chat with newer "+essChat.getDescription().getFullName());
public static void integrateChat(EssentialsChat instance) {
essChat = instance;
try {
Bukkit.getServer().getPluginManager().registerEvents(new LocalChatListener(), P.p);
P.p.log("Found and will integrate chat with newer " + essChat.getDescription().getFullName());
// curly braces used to be accepted by the format string EssentialsChat but no longer are, so... deal with chatTagReplaceString which might need updating
if (Conf.chatTagReplaceString.contains("{"))
{
Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]");
P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you.");
}
}
catch (NoSuchMethodError ex)
{
essChat = null;
}
}
// curly braces used to be accepted by the format string EssentialsChat but no longer are, so... deal with chatTagReplaceString which might need updating
if (Conf.chatTagReplaceString.contains("{")) {
Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]");
P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you.");
}
} catch (NoSuchMethodError ex) {
essChat = null;
}
}
private static class LocalChatListener implements Listener
{
@SuppressWarnings("unused")
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChat(EssentialsLocalChatEvent event)
{
Player speaker = event.getPlayer();
String format = event.getFormat();
format = format.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(speaker));
event.setFormat(format);
// NOTE: above doesn't do relation coloring. if/when we can get a local recipient list from EssentialsLocalChatEvent, we'll probably
// want to pass it on to FactionsPlayerListener.onPlayerChat(PlayerChatEvent event) rather than duplicating code
}
}
private static class LocalChatListener implements Listener {
@SuppressWarnings("unused")
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChat(EssentialsLocalChatEvent event) {
Player speaker = event.getPlayer();
String format = event.getFormat();
format = format.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(speaker));
event.setFormat(format);
// NOTE: above doesn't do relation coloring. if/when we can get a local recipient list from EssentialsLocalChatEvent, we'll probably
// want to pass it on to FactionsPlayerListener.onPlayerChat(PlayerChatEvent event) rather than duplicating code
}
}
}

View File

@@ -1,59 +1,47 @@
package com.massivecraft.factions.integration;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.P;
import com.earth2me.essentials.chat.EssentialsChat;
import com.earth2me.essentials.chat.IEssentialsChatListener;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.P;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
/*
* This Essentials integration handler is for older 2.x.x versions of Essentials which have "IEssentialsChatListener"
*/
public class EssentialsOldVersionFeatures
{
private static EssentialsChat essChat;
public class EssentialsOldVersionFeatures {
private static EssentialsChat essChat;
public static void integrateChat(EssentialsChat instance)
{
essChat = instance;
try
{
essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener()
{
public boolean shouldHandleThisChat(AsyncPlayerChatEvent event)
{
return P.p.shouldLetFactionsHandleThisChat(event);
}
public String modifyMessage(AsyncPlayerChatEvent event, Player target, String message)
{
return message.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTagRelation(event.getPlayer(), target)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(event.getPlayer()));
}
});
P.p.log("Found and will integrate chat with "+essChat.getDescription().getFullName());
public static void integrateChat(EssentialsChat instance) {
essChat = instance;
try {
essChat.addEssentialsChatListener("Factions", new IEssentialsChatListener() {
public boolean shouldHandleThisChat(AsyncPlayerChatEvent event) {
return P.p.shouldLetFactionsHandleThisChat(event);
}
// As of Essentials 2.8+, curly braces are not accepted and are instead replaced with square braces, so... deal with it
if (essChat.getDescription().getVersion().startsWith("2.8.") && Conf.chatTagReplaceString.contains("{"))
{
Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]");
P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you.");
}
}
catch (NoSuchMethodError ex)
{
essChat = null;
}
}
public String modifyMessage(AsyncPlayerChatEvent event, Player target, String message) {
return message.replace(Conf.chatTagReplaceString, P.p.getPlayerFactionTagRelation(event.getPlayer(), target)).replace("[FACTION_TITLE]", P.p.getPlayerTitle(event.getPlayer()));
}
});
P.p.log("Found and will integrate chat with " + essChat.getDescription().getFullName());
public static void unhookChat()
{
if (essChat != null)
{
essChat.removeEssentialsChatListener("Factions");
}
}
// As of Essentials 2.8+, curly braces are not accepted and are instead replaced with square braces, so... deal with it
if (essChat.getDescription().getVersion().startsWith("2.8.") && Conf.chatTagReplaceString.contains("{")) {
Conf.chatTagReplaceString = Conf.chatTagReplaceString.replace("{", "[").replace("}", "]");
P.p.log("NOTE: as of Essentials 2.8+, we've had to switch the default chat replacement tag from \"{FACTION}\" to \"[FACTION]\". This has automatically been updated for you.");
}
} catch (NoSuchMethodError ex) {
essChat = null;
}
}
public static void unhookChat() {
if (essChat != null) {
essChat.removeEssentialsChatListener("Factions");
}
}
}

View File

@@ -1,90 +1,72 @@
package com.massivecraft.factions.integration;
import com.griefcraft.lwc.LWC;
import com.griefcraft.lwc.LWCPlugin;
import com.massivecraft.factions.*;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.plugin.Plugin;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
public class LWCFeatures {
private static LWC lwc;
import com.griefcraft.lwc.LWC;
import com.griefcraft.lwc.LWCPlugin;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
public static void setup() {
Plugin test = Bukkit.getServer().getPluginManager().getPlugin("LWC");
if (test == null || !test.isEnabled()) return;
public class LWCFeatures
{
private static LWC lwc;
lwc = ((LWCPlugin) test).getLWC();
P.p.log("Successfully hooked into LWC!" + (Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\")."));
}
public static void setup()
{
Plugin test = Bukkit.getServer().getPluginManager().getPlugin("LWC");
if(test == null || !test.isEnabled()) return;
public static boolean getEnabled() {
return Conf.lwcIntegration && lwc != null;
}
lwc = ((LWCPlugin)test).getLWC();
P.p.log("Successfully hooked into LWC!"+(Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\")."));
}
public static void clearOtherChests(FLocation flocation, Faction faction) {
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
public static boolean getEnabled()
{
return Conf.lwcIntegration && lwc != null;
}
for (int x = 0; x < blocks.length; x++) {
if (blocks[x].getType() == Material.CHEST) {
chests.add(blocks[x].getBlock());
}
}
public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static void clearAllChests(FLocation flocation)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
lwc.findProtection(chests.get(x)).remove();
}
}
}
for (int x = 0; x < chests.size(); x++) {
if (lwc.findProtection(chests.get(x)) != null) {
if (!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static void clearAllChests(FLocation flocation) {
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
if (location.getWorld() == null) return; // world not loaded or something? cancel out to prevent error
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for (int x = 0; x < blocks.length; x++) {
if (blocks[x].getType() == Material.CHEST) {
chests.add(blocks[x].getBlock());
}
}
for (int x = 0; x < chests.size(); x++) {
if (lwc.findProtection(chests.get(x)) != null) {
lwc.findProtection(chests.get(x)).remove();
}
}
}
}

View File

@@ -1,329 +1,298 @@
package com.massivecraft.factions.integration;
import com.massivecraft.factions.*;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.gui.Color;
import org.getspout.spoutapi.player.SpoutPlayer;
import java.util.Set;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.P;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
import org.bukkit.entity.Player;
public class SpoutFeatures {
private transient static boolean spoutMe = false;
private transient static SpoutMainListener mainListener;
private transient static boolean listenersHooked;
import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role;
public static void setup() {
Plugin test = Bukkit.getServer().getPluginManager().getPlugin("Spout");
if (test == null || !test.isEnabled()) return;
import org.getspout.spoutapi.gui.Color;
import org.getspout.spoutapi.player.SpoutPlayer;
import org.getspout.spoutapi.SpoutManager;
setAvailable(true, test.getDescription().getFullName());
}
// set integration availability
public static void setAvailable(boolean enable, String pluginName) {
spoutMe = enable;
if (!spoutMe) return;
P.p.log("Found and will use features of " + pluginName);
if (!listenersHooked) {
listenersHooked = true;
mainListener = new SpoutMainListener();
Bukkit.getServer().getPluginManager().registerEvents(mainListener, P.p);
}
}
// If we're successfully hooked into Spout
public static boolean enabled() {
return spoutMe;
}
// If Spout is available and the specified Player is running the Spoutcraft client
public static boolean availableFor(Player player) {
return spoutMe && SpoutManager.getPlayer(player).isSpoutCraftEnabled();
}
public class SpoutFeatures
{
private transient static boolean spoutMe = false;
private transient static SpoutMainListener mainListener;
private transient static boolean listenersHooked;
// update displayed current territory for all players inside a specified chunk; if specified chunk is null, then simply update everyone online
public static void updateTerritoryDisplayLoc(FLocation fLoc) {
if (!enabled())
return;
public static void setup()
{
Plugin test = Bukkit.getServer().getPluginManager().getPlugin("Spout");
if (test == null || !test.isEnabled()) return;
Set<FPlayer> players = FPlayers.i.getOnline();
setAvailable(true, test.getDescription().getFullName());
}
for (FPlayer player : players) {
if (fLoc == null)
mainListener.updateTerritoryDisplay(player, false);
else if (player.getLastStoodAt().equals(fLoc))
mainListener.updateTerritoryDisplay(player, true);
}
}
// set integration availability
public static void setAvailable(boolean enable, String pluginName)
{
spoutMe = enable;
if (!spoutMe) return;
// update displayed current territory for specified player; returns false if unsuccessful
public static boolean updateTerritoryDisplay(FPlayer player) {
if (!enabled())
return false;
P.p.log("Found and will use features of "+pluginName);
return mainListener.updateTerritoryDisplay(player, true);
}
if (!listenersHooked)
{
listenersHooked = true;
mainListener = new SpoutMainListener();
Bukkit.getServer().getPluginManager().registerEvents(mainListener, P.p);
}
}
// update owner list for all players inside a specified chunk; if specified chunk is null, then simply update everyone online
public static void updateOwnerListLoc(FLocation fLoc) {
if (!enabled())
return;
// If we're successfully hooked into Spout
public static boolean enabled()
{
return spoutMe;
}
Set<FPlayer> players = FPlayers.i.getOnline();
// If Spout is available and the specified Player is running the Spoutcraft client
public static boolean availableFor(Player player)
{
return spoutMe && SpoutManager.getPlayer(player).isSpoutCraftEnabled();
}
for (FPlayer player : players) {
if (fLoc == null || player.getLastStoodAt().equals(fLoc))
mainListener.updateOwnerList(player);
}
}
// update owner list for specified player
public static void updateOwnerList(FPlayer player) {
if (!enabled())
return;
mainListener.updateOwnerList(player);
}
public static void playerDisconnect(FPlayer player) {
if (!enabled())
return;
mainListener.removeTerritoryLabels(player.getName());
}
// update displayed current territory for all players inside a specified chunk; if specified chunk is null, then simply update everyone online
public static void updateTerritoryDisplayLoc(FLocation fLoc)
{
if (!enabled())
return;
// update all appearances between every player
public static void updateAppearances() {
if (!enabled())
return;
Set<FPlayer> players = FPlayers.i.getOnline();
Set<FPlayer> players = FPlayers.i.getOnline();
for (FPlayer player : players)
{
if (fLoc == null)
mainListener.updateTerritoryDisplay(player, false);
else if (player.getLastStoodAt().equals(fLoc))
mainListener.updateTerritoryDisplay(player, true);
}
}
for (FPlayer playerA : players) {
for (FPlayer playerB : players) {
updateSingle(playerB, playerA);
}
}
}
// update displayed current territory for specified player; returns false if unsuccessful
public static boolean updateTerritoryDisplay(FPlayer player)
{
if (!enabled())
return false;
// update all appearances related to a specific player
public static void updateAppearances(Player player) {
if (!enabled() || player == null)
return;
return mainListener.updateTerritoryDisplay(player, true);
}
Set<FPlayer> players = FPlayers.i.getOnline();
FPlayer playerA = FPlayers.i.get(player);
// update owner list for all players inside a specified chunk; if specified chunk is null, then simply update everyone online
public static void updateOwnerListLoc(FLocation fLoc)
{
if (!enabled())
return;
for (FPlayer playerB : players) {
updateSingle(playerB, playerA);
updateSingle(playerA, playerB);
}
}
Set<FPlayer> players = FPlayers.i.getOnline();
// as above method, but with a delay added; useful for after-login update which doesn't always propagate if done immediately
public static void updateAppearancesShortly(final Player player) {
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, new Runnable() {
@Override
public void run() {
updateAppearances(player);
}
}, 100);
}
for (FPlayer player : players)
{
if (fLoc == null || player.getLastStoodAt().equals(fLoc))
mainListener.updateOwnerList(player);
}
}
// update all appearances related to a single faction
public static void updateAppearances(Faction faction) {
if (!enabled() || faction == null)
return;
// update owner list for specified player
public static void updateOwnerList(FPlayer player)
{
if (!enabled())
return;
Set<FPlayer> players = FPlayers.i.getOnline();
Faction factionA;
mainListener.updateOwnerList(player);
}
for (FPlayer playerA : players) {
factionA = playerA.getFaction();
public static void playerDisconnect(FPlayer player)
{
if (!enabled())
return;
for (FPlayer playerB : players) {
if (factionA != faction && playerB.getFaction() != faction)
continue;
mainListener.removeTerritoryLabels(player.getName());
}
updateSingle(playerB, playerA);
}
}
}
// update all appearances between two factions
public static void updateAppearances(Faction factionA, Faction factionB) {
if (!enabled() || factionA == null || factionB == null)
return;
for (FPlayer playerA : factionA.getFPlayersWhereOnline(true)) {
for (FPlayer playerB : factionB.getFPlayersWhereOnline(true)) {
updateSingle(playerB, playerA);
updateSingle(playerA, playerB);
}
}
}
// update all appearances between every player
public static void updateAppearances()
{
if (!enabled())
return;
// update a single appearance; internal use only by above public methods
private static void updateSingle(FPlayer viewer, FPlayer viewed) {
if (viewer == null || viewed == null)
return;
Set<FPlayer> players = FPlayers.i.getOnline();
Faction viewedFaction = viewed.getFaction();
if (viewedFaction == null)
return;
for (FPlayer playerA : players)
{
for (FPlayer playerB : players)
{
updateSingle(playerB, playerA);
}
}
}
// these still end up returning null on occasion at this point, mucking up the SpoutManager.getPlayer() method
if (viewer.getPlayer() == null || viewed.getPlayer() == null)
return;
// update all appearances related to a specific player
public static void updateAppearances(Player player)
{
if (!enabled() || player == null)
return;
SpoutPlayer pViewer = SpoutManager.getPlayer(viewer.getPlayer());
SpoutPlayer pViewed = SpoutManager.getPlayer(viewed.getPlayer());
if (pViewed == null || pViewer == null)
return;
Set<FPlayer> players = FPlayers.i.getOnline();
FPlayer playerA = FPlayers.i.get(player);
String viewedTitle = viewed.getTitle();
Role viewedRole = viewed.getRole();
for (FPlayer playerB : players)
{
updateSingle(playerB, playerA);
updateSingle(playerA, playerB);
}
}
if ((Conf.spoutFactionTagsOverNames || Conf.spoutFactionTitlesOverNames) && viewer != viewed) {
if (viewedFaction.isNormal()) {
String addTag = "";
if (Conf.spoutFactionTagsOverNames)
addTag += viewedFaction.getTag(viewed.getColorTo(viewer).toString() + "[") + "]";
// as above method, but with a delay added; useful for after-login update which doesn't always propagate if done immediately
public static void updateAppearancesShortly(final Player player)
{
P.p.getServer().getScheduler().scheduleSyncDelayedTask(P.p, new Runnable()
{
@Override
public void run()
{
updateAppearances(player);
}
}, 100);
}
String rolePrefix = viewedRole.getPrefix();
if (Conf.spoutFactionTitlesOverNames && (!viewedTitle.isEmpty() || !rolePrefix.isEmpty()))
addTag += (addTag.isEmpty() ? "" : " ") + viewedRole.getPrefix() + viewedTitle;
// update all appearances related to a single faction
public static void updateAppearances(Faction faction)
{
if (!enabled() || faction == null)
return;
pViewed.setTitleFor(pViewer, addTag + "\n" + pViewed.getDisplayName());
} else {
pViewed.setTitleFor(pViewer, pViewed.getDisplayName());
}
}
Set<FPlayer> players = FPlayers.i.getOnline();
Faction factionA;
if
(
(
Conf.spoutFactionAdminCapes
&&
viewedRole.equals(Role.ADMIN)
)
||
(
Conf.spoutFactionModeratorCapes
&&
viewedRole.equals(Role.MODERATOR)
)
) {
Relation relation = viewer.getRelationTo(viewed);
String cape = "";
if (!viewedFaction.isNormal()) {
// yeah, no cape if no faction
} else if (viewedFaction.isPeaceful())
cape = Conf.capePeaceful;
else if (relation.isNeutral())
cape = Conf.capeNeutral;
else if (relation.isMember())
cape = Conf.capeMember;
else if (relation.isEnemy())
cape = Conf.capeEnemy;
else if (relation.isAlly())
cape = Conf.capeAlly;
for (FPlayer playerA : players)
{
factionA = playerA.getFaction();
for (FPlayer playerB : players)
{
if (factionA != faction && playerB.getFaction() != faction)
continue;
updateSingle(playerB, playerA);
}
}
}
// update all appearances between two factions
public static void updateAppearances(Faction factionA, Faction factionB)
{
if (!enabled() || factionA == null || factionB == null)
return;
for (FPlayer playerA : factionA.getFPlayersWhereOnline(true))
{
for (FPlayer playerB : factionB.getFPlayersWhereOnline(true))
{
updateSingle(playerB, playerA);
updateSingle(playerA, playerB);
}
}
}
if (cape.isEmpty())
pViewed.resetCapeFor(pViewer);
else
pViewed.setCapeFor(pViewer, cape);
} else if (Conf.spoutFactionAdminCapes || Conf.spoutFactionModeratorCapes) {
pViewed.resetCapeFor(pViewer);
}
}
// update a single appearance; internal use only by above public methods
private static void updateSingle(FPlayer viewer, FPlayer viewed)
{
if (viewer == null || viewed == null)
return;
// method to convert a Bukkit ChatColor to a Spout Color
protected static Color getSpoutColor(ChatColor inColor, int alpha) {
if (inColor == null)
return SpoutFixedColor(191, 191, 191, alpha);
Faction viewedFaction = viewed.getFaction();
if (viewedFaction == null)
return;
switch (inColor.getChar()) {
case 0x1:
return SpoutFixedColor(0, 0, 191, alpha);
case 0x2:
return SpoutFixedColor(0, 191, 0, alpha);
case 0x3:
return SpoutFixedColor(0, 191, 191, alpha);
case 0x4:
return SpoutFixedColor(191, 0, 0, alpha);
case 0x5:
return SpoutFixedColor(191, 0, 191, alpha);
case 0x6:
return SpoutFixedColor(191, 191, 0, alpha);
case 0x7:
return SpoutFixedColor(191, 191, 191, alpha);
case 0x8:
return SpoutFixedColor(64, 64, 64, alpha);
case 0x9:
return SpoutFixedColor(64, 64, 255, alpha);
case 0xA:
return SpoutFixedColor(64, 255, 64, alpha);
case 0xB:
return SpoutFixedColor(64, 255, 255, alpha);
case 0xC:
return SpoutFixedColor(255, 64, 64, alpha);
case 0xD:
return SpoutFixedColor(255, 64, 255, alpha);
case 0xE:
return SpoutFixedColor(255, 255, 64, alpha);
case 0xF:
return SpoutFixedColor(255, 255, 255, alpha);
default:
return SpoutFixedColor(0, 0, 0, alpha);
}
}
// these still end up returning null on occasion at this point, mucking up the SpoutManager.getPlayer() method
if (viewer.getPlayer() == null || viewed.getPlayer() == null)
return;
SpoutPlayer pViewer = SpoutManager.getPlayer(viewer.getPlayer());
SpoutPlayer pViewed = SpoutManager.getPlayer(viewed.getPlayer());
if (pViewed == null || pViewer == null)
return;
String viewedTitle = viewed.getTitle();
Role viewedRole = viewed.getRole();
if ((Conf.spoutFactionTagsOverNames || Conf.spoutFactionTitlesOverNames) && viewer != viewed)
{
if (viewedFaction.isNormal())
{
String addTag = "";
if (Conf.spoutFactionTagsOverNames)
addTag += viewedFaction.getTag(viewed.getColorTo(viewer).toString() + "[") + "]";
String rolePrefix = viewedRole.getPrefix();
if (Conf.spoutFactionTitlesOverNames && (!viewedTitle.isEmpty() || !rolePrefix.isEmpty()))
addTag += (addTag.isEmpty() ? "" : " ") + viewedRole.getPrefix() + viewedTitle;
pViewed.setTitleFor(pViewer, addTag + "\n" + pViewed.getDisplayName());
}
else
{
pViewed.setTitleFor(pViewer, pViewed.getDisplayName());
}
}
if
(
(
Conf.spoutFactionAdminCapes
&&
viewedRole.equals(Role.ADMIN)
)
||
(
Conf.spoutFactionModeratorCapes
&&
viewedRole.equals(Role.MODERATOR)
)
)
{
Relation relation = viewer.getRelationTo(viewed);
String cape = "";
if (!viewedFaction.isNormal())
{
// yeah, no cape if no faction
}
else if (viewedFaction.isPeaceful())
cape = Conf.capePeaceful;
else if (relation.isNeutral())
cape = Conf.capeNeutral;
else if (relation.isMember())
cape = Conf.capeMember;
else if (relation.isEnemy())
cape = Conf.capeEnemy;
else if (relation.isAlly())
cape = Conf.capeAlly;
if (cape.isEmpty())
pViewed.resetCapeFor(pViewer);
else
pViewed.setCapeFor(pViewer, cape);
}
else if (Conf.spoutFactionAdminCapes || Conf.spoutFactionModeratorCapes)
{
pViewed.resetCapeFor(pViewer);
}
}
// method to convert a Bukkit ChatColor to a Spout Color
protected static Color getSpoutColor(ChatColor inColor, int alpha)
{
if (inColor == null)
return SpoutFixedColor(191, 191, 191, alpha);
switch (inColor.getChar())
{
case 0x1: return SpoutFixedColor(0, 0, 191, alpha);
case 0x2: return SpoutFixedColor(0, 191, 0, alpha);
case 0x3: return SpoutFixedColor(0, 191, 191, alpha);
case 0x4: return SpoutFixedColor(191, 0, 0, alpha);
case 0x5: return SpoutFixedColor(191, 0, 191, alpha);
case 0x6: return SpoutFixedColor(191, 191, 0, alpha);
case 0x7: return SpoutFixedColor(191, 191, 191, alpha);
case 0x8: return SpoutFixedColor(64, 64, 64, alpha);
case 0x9: return SpoutFixedColor(64, 64, 255, alpha);
case 0xA: return SpoutFixedColor(64, 255, 64, alpha);
case 0xB: return SpoutFixedColor(64, 255, 255, alpha);
case 0xC: return SpoutFixedColor(255, 64, 64, alpha);
case 0xD: return SpoutFixedColor(255, 64, 255, alpha);
case 0xE: return SpoutFixedColor(255, 255, 64, alpha);
case 0xF: return SpoutFixedColor(255, 255, 255, alpha);
default: return SpoutFixedColor(0, 0, 0, alpha);
}
}
private static Color SpoutFixedColor(int r, int g, int b, int a)
{
return new Color(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
}
private static Color SpoutFixedColor(int r, int g, int b, int a) {
return new Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}
}

View File

@@ -1,247 +1,217 @@
package com.massivecraft.factions.integration;
import java.util.HashMap;
import java.util.Map;
import com.massivecraft.factions.*;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.event.spout.SpoutCraftEnableEvent;
import org.getspout.spoutapi.gui.GenericLabel;
import org.getspout.spoutapi.player.SpoutPlayer;
import org.getspout.spoutapi.SpoutManager;
import java.util.HashMap;
import java.util.Map;
public class SpoutMainListener implements Listener
{
@EventHandler(priority = EventPriority.NORMAL)
public void onSpoutCraftEnable(SpoutCraftEnableEvent event)
{
final FPlayer me = FPlayers.i.get(event.getPlayer());
public class SpoutMainListener implements Listener {
@EventHandler(priority = EventPriority.NORMAL)
public void onSpoutCraftEnable(SpoutCraftEnableEvent event) {
final FPlayer me = FPlayers.i.get(event.getPlayer());
SpoutFeatures.updateAppearances(me.getPlayer());
updateTerritoryDisplay(me, true);
}
SpoutFeatures.updateAppearances(me.getPlayer());
updateTerritoryDisplay(me, true);
}
//-----------------------------------------------------------------------------------------//
// Everything below this is handled in here to prevent errors on servers not running Spout
//-----------------------------------------------------------------------------------------//
//-----------------------------------------------------------------------------------------//
// Everything below this is handled in here to prevent errors on servers not running Spout
//-----------------------------------------------------------------------------------------//
private transient static Map<String, GenericLabel> territoryLabels = new HashMap<String, GenericLabel>();
private transient static Map<String, NoticeLabel> territoryChangeLabels = new HashMap<String, NoticeLabel>();
private transient static Map<String, GenericLabel> ownerLabels = new HashMap<String, GenericLabel>();
private final static int SCREEN_WIDTH = 427;
private transient static Map<String, GenericLabel> territoryLabels = new HashMap<String, GenericLabel>();
private transient static Map<String, NoticeLabel> territoryChangeLabels = new HashMap<String, NoticeLabel>();
private transient static Map<String, GenericLabel> ownerLabels = new HashMap<String, GenericLabel>();
private final static int SCREEN_WIDTH = 427;
// private final static int SCREEN_HEIGHT = 240;
public boolean updateTerritoryDisplay(FPlayer player, boolean notify)
{
Player p = player.getPlayer();
if (p == null)
return false;
public boolean updateTerritoryDisplay(FPlayer player, boolean notify) {
Player p = player.getPlayer();
if (p == null)
return false;
SpoutPlayer sPlayer = SpoutManager.getPlayer(p);
if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && ! Conf.spoutTerritoryNoticeShow))
return false;
SpoutPlayer sPlayer = SpoutManager.getPlayer(p);
if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && !Conf.spoutTerritoryNoticeShow))
return false;
doLabels(player, sPlayer, notify);
doLabels(player, sPlayer, notify);
return true;
}
return true;
}
public void updateOwnerList(FPlayer player)
{
SpoutPlayer sPlayer = SpoutManager.getPlayer(player.getPlayer());
if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && ! Conf.spoutTerritoryNoticeShow))
return;
public void updateOwnerList(FPlayer player) {
SpoutPlayer sPlayer = SpoutManager.getPlayer(player.getPlayer());
if (!sPlayer.isSpoutCraftEnabled() || (Conf.spoutTerritoryDisplaySize <= 0 && !Conf.spoutTerritoryNoticeShow))
return;
FLocation here = player.getLastStoodAt();
Faction factionHere = Board.getFactionAt(here);
FLocation here = player.getLastStoodAt();
Faction factionHere = Board.getFactionAt(here);
doOwnerList(player, sPlayer, here, factionHere);
doOwnerList(player, sPlayer, here, factionHere);
return;
}
return;
}
public void removeTerritoryLabels(String playerName)
{
territoryLabels.remove(playerName);
territoryChangeLabels.remove(playerName);
ownerLabels.remove(playerName);
}
public void removeTerritoryLabels(String playerName) {
territoryLabels.remove(playerName);
territoryChangeLabels.remove(playerName);
ownerLabels.remove(playerName);
}
private void doLabels(FPlayer player, SpoutPlayer sPlayer, boolean notify)
{
FLocation here = player.getLastStoodAt();
Faction factionHere = Board.getFactionAt(here);
String tag = factionHere.getColorTo(player).toString() + factionHere.getTag();
private void doLabels(FPlayer player, SpoutPlayer sPlayer, boolean notify) {
FLocation here = player.getLastStoodAt();
Faction factionHere = Board.getFactionAt(here);
String tag = factionHere.getColorTo(player).toString() + factionHere.getTag();
// ----------------------
// Main territory display
// ----------------------
if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0)
{
GenericLabel label;
if (territoryLabels.containsKey(player.getName()))
label = territoryLabels.get(player.getName());
else
{
label = new GenericLabel();
label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning
label.setScale(Conf.spoutTerritoryDisplaySize);
// ----------------------
// Main territory display
// ----------------------
if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0) {
GenericLabel label;
if (territoryLabels.containsKey(player.getName()))
label = territoryLabels.get(player.getName());
else {
label = new GenericLabel();
label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning
label.setScale(Conf.spoutTerritoryDisplaySize);
sPlayer.getMainScreen().attachWidget(P.p, label);
territoryLabels.put(player.getName(), label);
}
sPlayer.getMainScreen().attachWidget(P.p, label);
territoryLabels.put(player.getName(), label);
}
String msg = tag;
String msg = tag;
if (Conf.spoutTerritoryDisplayShowDescription && !factionHere.getDescription().isEmpty())
msg += " - " + factionHere.getDescription();
if (Conf.spoutTerritoryDisplayShowDescription && !factionHere.getDescription().isEmpty())
msg += " - " + factionHere.getDescription();
label.setText(msg);
alignLabel(label, msg);
label.setDirty(true);
}
label.setText(msg);
alignLabel(label, msg);
label.setDirty(true);
}
// -----------------------
// Fading territory notice
// -----------------------
if (notify && Conf.spoutTerritoryNoticeShow && Conf.spoutTerritoryNoticeSize > 0)
{
NoticeLabel label;
if (territoryChangeLabels.containsKey(player.getName()))
label = territoryChangeLabels.get(player.getName());
else
{
label = new NoticeLabel(Conf.spoutTerritoryNoticeLeaveAfterSeconds);
label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning
label.setScale(Conf.spoutTerritoryNoticeSize);
label.setY(Conf.spoutTerritoryNoticeTop);
sPlayer.getMainScreen().attachWidget(P.p, label);
territoryChangeLabels.put(player.getName(), label);
}
// -----------------------
// Fading territory notice
// -----------------------
if (notify && Conf.spoutTerritoryNoticeShow && Conf.spoutTerritoryNoticeSize > 0) {
NoticeLabel label;
if (territoryChangeLabels.containsKey(player.getName()))
label = territoryChangeLabels.get(player.getName());
else {
label = new NoticeLabel(Conf.spoutTerritoryNoticeLeaveAfterSeconds);
label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning
label.setScale(Conf.spoutTerritoryNoticeSize);
label.setY(Conf.spoutTerritoryNoticeTop);
sPlayer.getMainScreen().attachWidget(P.p, label);
territoryChangeLabels.put(player.getName(), label);
}
String msg = tag;
String msg = tag;
if (Conf.spoutTerritoryNoticeShowDescription && !factionHere.getDescription().isEmpty())
msg += " - " + factionHere.getDescription();
if (Conf.spoutTerritoryNoticeShowDescription && !factionHere.getDescription().isEmpty())
msg += " - " + factionHere.getDescription();
label.setText(msg);
alignLabel(label, msg, 2);
label.resetNotice();
label.setDirty(true);
}
label.setText(msg);
alignLabel(label, msg, 2);
label.resetNotice();
label.setDirty(true);
}
// and owner list, of course
doOwnerList(player, sPlayer, here, factionHere);
}
private void doOwnerList(FPlayer player, SpoutPlayer sPlayer, FLocation here, Faction factionHere)
{
// ----------
// Owner list
// ----------
if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0 && Conf.spoutTerritoryOwnersShow && Conf.ownedAreasEnabled)
{
GenericLabel label;
if (ownerLabels.containsKey(player.getName()))
label = ownerLabels.get(player.getName());
else
{
label = new GenericLabel();
label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning
label.setScale(Conf.spoutTerritoryDisplaySize);
label.setY((int)(10 * Conf.spoutTerritoryDisplaySize));
sPlayer.getMainScreen().attachWidget(P.p, label);
ownerLabels.put(player.getName(), label);
}
// and owner list, of course
doOwnerList(player, sPlayer, here, factionHere);
}
String msg = "";
private void doOwnerList(FPlayer player, SpoutPlayer sPlayer, FLocation here, Faction factionHere) {
// ----------
// Owner list
// ----------
if (Conf.spoutTerritoryDisplayPosition > 0 && Conf.spoutTerritoryDisplaySize > 0 && Conf.spoutTerritoryOwnersShow && Conf.ownedAreasEnabled) {
GenericLabel label;
if (ownerLabels.containsKey(player.getName()))
label = ownerLabels.get(player.getName());
else {
label = new GenericLabel();
label.setWidth(1).setHeight(1); // prevent Spout's questionable new "no default size" warning
label.setScale(Conf.spoutTerritoryDisplaySize);
label.setY((int) (10 * Conf.spoutTerritoryDisplaySize));
sPlayer.getMainScreen().attachWidget(P.p, label);
ownerLabels.put(player.getName(), label);
}
if (player.getFaction() == factionHere)
{
msg = factionHere.getOwnerListString(here);
String msg = "";
if (!msg.isEmpty())
msg = Conf.ownedLandMessage + msg;
}
if (player.getFaction() == factionHere) {
msg = factionHere.getOwnerListString(here);
label.setText(msg);
alignLabel(label, msg);
label.setDirty(true);
}
}
if (!msg.isEmpty())
msg = Conf.ownedLandMessage + msg;
}
label.setText(msg);
alignLabel(label, msg);
label.setDirty(true);
}
}
// this is only necessary because Spout text size scaling is currently bugged and breaks their built-in alignment methods
public void alignLabel(GenericLabel label, String text)
{
alignLabel(label, text, Conf.spoutTerritoryDisplayPosition);
}
public void alignLabel(GenericLabel label, String text, int alignment)
{
int labelWidth = (int)((float)GenericLabel.getStringWidth(text) * Conf.spoutTerritoryDisplaySize);
if (labelWidth > SCREEN_WIDTH)
{
label.setX(0);
return;
}
// this is only necessary because Spout text size scaling is currently bugged and breaks their built-in alignment methods
public void alignLabel(GenericLabel label, String text) {
alignLabel(label, text, Conf.spoutTerritoryDisplayPosition);
}
switch (alignment)
{
case 1: // left aligned
label.setX(0);
break;
case 2: // center aligned
label.setX((SCREEN_WIDTH - labelWidth) / 2);
break;
default: // right aligned
label.setX(SCREEN_WIDTH - labelWidth);
}
}
public void alignLabel(GenericLabel label, String text, int alignment) {
int labelWidth = (int) ((float) GenericLabel.getStringWidth(text) * Conf.spoutTerritoryDisplaySize);
if (labelWidth > SCREEN_WIDTH) {
label.setX(0);
return;
}
switch (alignment) {
case 1: // left aligned
label.setX(0);
break;
case 2: // center aligned
label.setX((SCREEN_WIDTH - labelWidth) / 2);
break;
default: // right aligned
label.setX(SCREEN_WIDTH - labelWidth);
}
}
private static class NoticeLabel extends GenericLabel
{
private int initial;
private int countdown; // current delay countdown
private static class NoticeLabel extends GenericLabel {
private int initial;
private int countdown; // current delay countdown
public NoticeLabel(float secondsOfLife)
{
initial = (int)(secondsOfLife * 20);
resetNotice();
}
public NoticeLabel(float secondsOfLife) {
initial = (int) (secondsOfLife * 20);
resetNotice();
}
public final void resetNotice()
{
countdown = initial;
}
public final void resetNotice() {
countdown = initial;
}
@Override
public void onTick()
{
if (countdown <= 0)
return;
@Override
public void onTick() {
if (countdown <= 0)
return;
this.countdown -= 1;
this.countdown -= 1;
if (this.countdown <= 0)
{
this.setText("");
this.setDirty(true);
}
}
}
if (this.countdown <= 0) {
this.setText("");
this.setDirty(true);
}
}
}
}

View File

@@ -1,152 +1,133 @@
package com.massivecraft.factions.integration;
import com.massivecraft.factions.P;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import static com.sk89q.worldguard.bukkit.BukkitUtil.*;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.BlockVector;
import org.bukkit.World;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
import org.bukkit.entity.Player;
/*
* Worldguard Region Checking
* Author: Spathizilla
*/
public class Worldguard
{
private static WorldGuardPlugin wg;
private static boolean enabled = false;
public class Worldguard {
private static WorldGuardPlugin wg;
private static boolean enabled = false;
public static void init(Plugin plugin)
{
Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard");
if (wgplug == null || !(wgplug instanceof WorldGuardPlugin))
{
enabled = false;
wg = null;
P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled.");
}
else
{
wg = (WorldGuardPlugin) wgplug;
enabled = true;
P.p.log("Successfully hooked to WorldGuard.");
}
}
public static void init(Plugin plugin) {
Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard");
if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) {
enabled = false;
wg = null;
P.p.log("Could not hook to WorldGuard. WorldGuard checks are disabled.");
} else {
wg = (WorldGuardPlugin) wgplug;
enabled = true;
P.p.log("Successfully hooked to WorldGuard.");
}
}
public static boolean isEnabled()
{
return enabled;
}
public static boolean isEnabled() {
return enabled;
}
// PVP Flag check
// Returns:
// True: PVP is allowed
// False: PVP is disallowed
public static boolean isPVP(Player player)
{
if( ! enabled)
{
// No WG hooks so we'll always bypass this check.
return true;
}
// PVP Flag check
// Returns:
// True: PVP is allowed
// False: PVP is disallowed
public static boolean isPVP(Player player) {
if (!enabled) {
// No WG hooks so we'll always bypass this check.
return true;
}
Location loc = player.getLocation();
World world = loc.getWorld();
Vector pt = toVector(loc);
Location loc = player.getLocation();
World world = loc.getWorld();
Vector pt = toVector(loc);
RegionManager regionManager = wg.getRegionManager(world);
ApplicableRegionSet set = regionManager.getApplicableRegions(pt);
return set.allows(DefaultFlag.PVP);
}
RegionManager regionManager = wg.getRegionManager(world);
ApplicableRegionSet set = regionManager.getApplicableRegions(pt);
return set.allows(DefaultFlag.PVP);
}
// Check if player can build at location by worldguards rules.
// Returns:
// True: Player can build in the region.
// False: Player can not build in the region.
public static boolean playerCanBuild(Player player, Location loc)
{
if( ! enabled)
{
// No WG hooks so we'll always bypass this check.
return false;
}
World world = loc.getWorld();
Vector pt = toVector(loc);
if (wg.getRegionManager(world).getApplicableRegions(pt).size() > 0)
return wg.canBuild(player, loc);
return false;
}
// Check if player can build at location by worldguards rules.
// Returns:
// True: Player can build in the region.
// False: Player can not build in the region.
public static boolean playerCanBuild(Player player, Location loc) {
if (!enabled) {
// No WG hooks so we'll always bypass this check.
return false;
}
// Check for Regions in chunk the chunk
// Returns:
// True: Regions found within chunk
// False: No regions found within chunk
public static boolean checkForRegionsInChunk(Location loc)
{
if( ! enabled)
{
// No WG hooks so we'll always bypass this check.
return false;
}
World world = loc.getWorld();
Vector pt = toVector(loc);
World world = loc.getWorld();
Chunk chunk = world.getChunkAt(loc);
int minChunkX = chunk.getX() << 4;
int minChunkZ = chunk.getZ() << 4;
int maxChunkX = minChunkX + 15;
int maxChunkZ = minChunkZ + 15;
if (wg.getRegionManager(world).getApplicableRegions(pt).size() > 0)
return wg.canBuild(player, loc);
return false;
}
int worldHeight = world.getMaxHeight(); // Allow for heights other than default
// Check for Regions in chunk the chunk
// Returns:
// True: Regions found within chunk
// False: No regions found within chunk
public static boolean checkForRegionsInChunk(Location loc) {
if (!enabled) {
// No WG hooks so we'll always bypass this check.
return false;
}
BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ);
BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ);
World world = loc.getWorld();
Chunk chunk = world.getChunkAt(loc);
int minChunkX = chunk.getX() << 4;
int minChunkZ = chunk.getZ() << 4;
int maxChunkX = minChunkX + 15;
int maxChunkZ = minChunkZ + 15;
RegionManager regionManager = wg.getRegionManager(world);
ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk);
Map<String, ProtectedRegion> allregions = regionManager.getRegions();
List<ProtectedRegion> allregionslist = new ArrayList<ProtectedRegion>(allregions.values());
List<ProtectedRegion> overlaps;
boolean foundregions = false;
int worldHeight = world.getMaxHeight(); // Allow for heights other than default
try
{
overlaps = region.getIntersectingRegions(allregionslist);
if(overlaps == null || overlaps.isEmpty())
{
foundregions = false;
}
else
{
foundregions = true;
}
}
catch (Exception e)
{
e.printStackTrace();
}
BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ);
BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ);
region = null;
allregionslist = null;
overlaps = null;
RegionManager regionManager = wg.getRegionManager(world);
ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk);
Map<String, ProtectedRegion> allregions = regionManager.getRegions();
List<ProtectedRegion> allregionslist = new ArrayList<ProtectedRegion>(allregions.values());
List<ProtectedRegion> overlaps;
boolean foundregions = false;
return foundregions;
}
try {
overlaps = region.getIntersectingRegions(allregionslist);
if (overlaps == null || overlaps.isEmpty()) {
foundregions = false;
} else {
foundregions = true;
}
} catch (Exception e) {
e.printStackTrace();
}
region = null;
allregionslist = null;
overlaps = null;
return foundregions;
}
}

View File

@@ -1,19 +1,15 @@
package com.massivecraft.factions.integration.capi;
import com.massivecraft.factions.P;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import com.massivecraft.factions.P;
public class CapiFeatures
{
public static void setup()
{
Plugin plug = Bukkit.getServer().getPluginManager().getPlugin("capi");
if (plug != null && plug.getClass().getName().equals("com.massivecraft.capi.P"))
{
P.p.log("Integration with the CAPI plugin was successful");
Bukkit.getPluginManager().registerEvents(new PluginCapiListener(P.p), P.p);
}
}
public class CapiFeatures {
public static void setup() {
Plugin plug = Bukkit.getServer().getPluginManager().getPlugin("capi");
if (plug != null && plug.getClass().getName().equals("com.massivecraft.capi.P")) {
P.p.log("Integration with the CAPI plugin was successful");
Bukkit.getPluginManager().registerEvents(new PluginCapiListener(P.p), P.p);
}
}
}

View File

@@ -1,14 +1,5 @@
package com.massivecraft.factions.integration.capi;
import java.util.LinkedHashSet;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.massivecraft.capi.Channel;
import com.massivecraft.capi.Channels;
import com.massivecraft.capi.events.CAPIListChannelsEvent;
@@ -20,106 +11,99 @@ import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Relation;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class PluginCapiListener implements Listener
{
P p;
Set<String> myChannelIds = new LinkedHashSet<String>();
public PluginCapiListener(P p)
{
this.p = p;
myChannelIds.add("faction");
myChannelIds.add("allies");
}
private String replacePlayerTags(String format, FPlayer me, FPlayer you)
{
String meFactionTag = me.getChatTag(you);
format = format.replace("{ME_FACTIONTAG}", meFactionTag.length() == 0 ? "" : meFactionTag);
format = format.replace("{ME_FACTIONTAG_PADR}", meFactionTag.length() == 0 ? "" : meFactionTag+" ");
format = format.replace("{ME_FACTIONTAG_PADL}", meFactionTag.length() == 0 ? "" : " "+meFactionTag);
format = format.replace("{ME_FACTIONTAG_PADB}", meFactionTag.length() == 0 ? "" : " "+meFactionTag+" ");
import java.util.LinkedHashSet;
import java.util.Set;
String youFactionTag = you.getChatTag(me);
format = format.replace("{YOU_FACTIONTAG}", youFactionTag.length() == 0 ? "" : youFactionTag);
format = format.replace("{YOU_FACTIONTAG_PADR}", youFactionTag.length() == 0 ? "" : youFactionTag+" ");
format = format.replace("{YOU_FACTIONTAG_PADL}", youFactionTag.length() == 0 ? "" : " "+youFactionTag);
format = format.replace("{YOU_FACTIONTAG_PADB}", youFactionTag.length() == 0 ? "" : " "+youFactionTag+" ");
return format;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onListChannelsEvent(CAPIListChannelsEvent event)
{
for (Channel c : Channels.i.getAll())
{
if (myChannelIds.contains(c.getId()))
{
event.getChannels().add(c);
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onMessageToChannel(CAPIMessageToChannelEvent event)
{
if (event.isCancelled()) return;
if ( ! myChannelIds.contains(event.getChannel().getId())) return;
Player me = event.getMe();
FPlayer fme = FPlayers.i.get(me);
Faction myFaction = fme.getFaction();
if (event.getChannel().getId().equals("faction") && myFaction.isNormal())
{
event.getThem().addAll(myFaction.getOnlinePlayers());
public class PluginCapiListener implements Listener {
P p;
// Send to any players who are spying chat... could probably be implemented better than this
for (FPlayer fplayer : FPlayers.i.getOnline())
{
if(fplayer.isSpyingChat() && fplayer.getFaction() != myFaction)
fplayer.sendMessage("[FCspy] "+myFaction.getTag()+": "+event.getMessage());
}
}
else if (event.getChannel().getId().equals("allies"))
{
for (Player somePlayer : Bukkit.getServer().getOnlinePlayers())
{
FPlayer someFPlayer = FPlayers.i.get(somePlayer);
if (someFPlayer.getRelationTo(fme).isAtLeast(Relation.ALLY))
event.getThem().add(somePlayer);
// Send to any players who are spying chat
else if(someFPlayer.isSpyingChat())
someFPlayer.sendMessage("[ACspy]: " + event.getMessage());
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onMessageToPlayer(CAPIMessageToPlayerEvent event)
{
if (event.isCancelled()) return;
event.setFormat(this.replacePlayerTags(event.getFormat(), FPlayers.i.get(event.getMe()), FPlayers.i.get(event.getYou())));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onSelectChannel(CAPISelectChannelEvent event)
{
if (event.isCancelled()) return;
String channelId = event.getChannel().getId();
if ( ! myChannelIds.contains(channelId)) return;
Player me = event.getMe();
FPlayer fme = FPlayers.i.get(me);
if ( ! fme.hasFaction())
{
event.setFailMessage(p.txt.parse("<b>You must be member in a faction to use this channel."));
event.setCancelled(true);
}
}
Set<String> myChannelIds = new LinkedHashSet<String>();
public PluginCapiListener(P p) {
this.p = p;
myChannelIds.add("faction");
myChannelIds.add("allies");
}
private String replacePlayerTags(String format, FPlayer me, FPlayer you) {
String meFactionTag = me.getChatTag(you);
format = format.replace("{ME_FACTIONTAG}", meFactionTag.length() == 0 ? "" : meFactionTag);
format = format.replace("{ME_FACTIONTAG_PADR}", meFactionTag.length() == 0 ? "" : meFactionTag + " ");
format = format.replace("{ME_FACTIONTAG_PADL}", meFactionTag.length() == 0 ? "" : " " + meFactionTag);
format = format.replace("{ME_FACTIONTAG_PADB}", meFactionTag.length() == 0 ? "" : " " + meFactionTag + " ");
String youFactionTag = you.getChatTag(me);
format = format.replace("{YOU_FACTIONTAG}", youFactionTag.length() == 0 ? "" : youFactionTag);
format = format.replace("{YOU_FACTIONTAG_PADR}", youFactionTag.length() == 0 ? "" : youFactionTag + " ");
format = format.replace("{YOU_FACTIONTAG_PADL}", youFactionTag.length() == 0 ? "" : " " + youFactionTag);
format = format.replace("{YOU_FACTIONTAG_PADB}", youFactionTag.length() == 0 ? "" : " " + youFactionTag + " ");
return format;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onListChannelsEvent(CAPIListChannelsEvent event) {
for (Channel c : Channels.i.getAll()) {
if (myChannelIds.contains(c.getId())) {
event.getChannels().add(c);
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onMessageToChannel(CAPIMessageToChannelEvent event) {
if (event.isCancelled()) return;
if (!myChannelIds.contains(event.getChannel().getId())) return;
Player me = event.getMe();
FPlayer fme = FPlayers.i.get(me);
Faction myFaction = fme.getFaction();
if (event.getChannel().getId().equals("faction") && myFaction.isNormal()) {
event.getThem().addAll(myFaction.getOnlinePlayers());
// Send to any players who are spying chat... could probably be implemented better than this
for (FPlayer fplayer : FPlayers.i.getOnline()) {
if (fplayer.isSpyingChat() && fplayer.getFaction() != myFaction)
fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + event.getMessage());
}
} else if (event.getChannel().getId().equals("allies")) {
for (Player somePlayer : Bukkit.getServer().getOnlinePlayers()) {
FPlayer someFPlayer = FPlayers.i.get(somePlayer);
if (someFPlayer.getRelationTo(fme).isAtLeast(Relation.ALLY))
event.getThem().add(somePlayer);
// Send to any players who are spying chat
else if (someFPlayer.isSpyingChat())
someFPlayer.sendMessage("[ACspy]: " + event.getMessage());
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onMessageToPlayer(CAPIMessageToPlayerEvent event) {
if (event.isCancelled()) return;
event.setFormat(this.replacePlayerTags(event.getFormat(), FPlayers.i.get(event.getMe()), FPlayers.i.get(event.getYou())));
}
@EventHandler(priority = EventPriority.NORMAL)
public void onSelectChannel(CAPISelectChannelEvent event) {
if (event.isCancelled()) return;
String channelId = event.getChannel().getId();
if (!myChannelIds.contains(channelId)) return;
Player me = event.getMe();
FPlayer fme = FPlayers.i.get(me);
if (!fme.hasFaction()) {
event.setFailMessage(p.txt.parse("<b>You must be member in a faction to use this channel."));
event.setCancelled(true);
}
}
}