use of com.denizenscript.denizencore.objects.core.ScriptTag in project Denizen-For-Bukkit by DenizenScript.
the class ItemScriptContainer method getItemFrom.
public ItemTag getItemFrom(TagContext context) {
if (isProcessing) {
Debug.echoError("Item script contains (or chains to) a reference to itself. Cannot process.");
return null;
}
if (context == null) {
context = new BukkitTagContext(null, null, new ScriptTag(this));
} else {
context = new BukkitTagContext((BukkitTagContext) context);
context.script = new ScriptTag(this);
}
// Try to use this script to make an item.
ItemTag stack;
isProcessing = true;
try {
if (!contains("material", String.class)) {
Debug.echoError("Item script '" + getName() + "' does not contain a material. Script cannot function.");
return null;
}
// Check validity of material
String material = TagManager.tag(getString("material"), context);
if (material.startsWith("m@")) {
material = material.substring(2);
}
stack = ItemTag.valueOf(material, this);
// Make sure we're working with a valid base ItemStack
if (stack == null) {
Debug.echoError("Item script '" + getName() + "' contains an invalid or incorrect material '" + material + "' (did you spell the material name wrong?). Script cannot function.");
return null;
}
// Handle listed mechanisms
if (contains("mechanisms", Map.class)) {
YamlConfiguration mechs = getConfigurationSection("mechanisms");
for (StringHolder key : mechs.getKeys(false)) {
ObjectTag obj = CoreUtilities.objectToTagForm(mechs.get(key.low), context, true, true);
stack.safeAdjust(new Mechanism(key.low, obj, context));
}
}
// Set Display Name
if (contains("display name", String.class)) {
String displayName = TagManager.tag(getString("display name"), context);
NMSHandler.getItemHelper().setDisplayName(stack, displayName);
}
// Set if the object is bound to the player
if (contains("bound", String.class)) {
Deprecations.boundWarning.warn(context);
}
// Set Lore
if (contains("lore", List.class)) {
List<String> lore = NMSHandler.getItemHelper().getLore(stack);
if (lore == null) {
lore = new ArrayList<>();
}
for (String line : getStringList("lore")) {
line = TagManager.tag(line, context);
lore.add(line);
}
CoreUtilities.fixNewLinesToListSeparation(lore);
NMSHandler.getItemHelper().setLore(stack, lore);
}
// Set Durability
if (contains("durability", String.class)) {
short durability = Short.valueOf(getString("durability"));
stack.setDurability(durability);
}
// Set Enchantments
if (contains("enchantments", List.class)) {
for (String enchantment : getStringList("enchantments")) {
enchantment = TagManager.tag(enchantment, context);
try {
// Build enchantment context
int level = 1;
int colon = enchantment.lastIndexOf(':');
if (colon == -1) {
Debug.echoError("Item script '" + getName() + "' has enchantment '" + enchantment + "' without a level.");
} else {
level = Integer.valueOf(enchantment.substring(colon + 1).replace(" ", ""));
enchantment = enchantment.substring(0, colon).replace(" ", "");
}
// Add enchantment
EnchantmentTag ench = EnchantmentTag.valueOf(enchantment, context);
if (ench == null) {
Debug.echoError("Item script '" + getName() + "' specifies enchantment '" + enchantment + "' which is invalid.");
continue;
}
if (stack.getBukkitMaterial() == Material.ENCHANTED_BOOK) {
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta();
meta.addStoredEnchant(ench.enchantment, level, true);
stack.setItemMeta(meta);
} else {
stack.getItemStack().addUnsafeEnchantment(ench.enchantment, level);
stack.resetCache();
}
} catch (Exception ex) {
Debug.echoError("While constructing item script '" + getName() + "', encountered error while applying enchantment '" + enchantment + "':");
Debug.echoError(ex);
}
}
}
// Set Color
if (contains("color", String.class)) {
Deprecations.itemScriptColor.warn(context);
String color = TagManager.tag(getString("color"), context);
LeatherColorer.colorArmor(stack, color);
}
// Set Book
if (contains("book", String.class)) {
BookScriptContainer book = ScriptRegistry.getScriptContainer(TagManager.tag(getString("book"), context).replace("s@", ""));
stack = book.writeBookTo(stack, context);
}
if (contains("flags", Map.class)) {
YamlConfiguration flagSection = getConfigurationSection("flags");
AbstractFlagTracker tracker = stack.getFlagTracker();
for (StringHolder key : flagSection.getKeys(false)) {
tracker.setFlag(key.str, CoreUtilities.objectToTagForm(flagSection.get(key.str), context, true, true), null);
}
stack.reapplyTracker(tracker);
}
stack.setItemScript(this);
} catch (Exception e) {
Debug.echoError("Woah! An exception has been called with this item script!");
Debug.echoError(e);
stack = null;
} finally {
isProcessing = false;
}
return stack;
}
use of com.denizenscript.denizencore.objects.core.ScriptTag in project Denizen-For-Bukkit by DenizenScript.
the class EntityScriptContainer method getEntityFrom.
public EntityTag getEntityFrom(PlayerTag player, NPCTag npc) {
EntityTag entity;
try {
TagContext context = new BukkitTagContext(player, npc, new ScriptTag(this));
if (contains("entity_type", String.class)) {
String entityType = TagManager.tag((getString("entity_type", "")), context);
entity = EntityTag.valueOf(entityType, context);
} else {
throw new Exception("Missing entity_type argument!");
}
if (contains("flags", Map.class)) {
YamlConfiguration flagSection = getConfigurationSection("flags");
MapTagFlagTracker tracker = new MapTagFlagTracker();
for (StringHolder key : flagSection.getKeys(false)) {
tracker.setFlag(key.str, CoreUtilities.objectToTagForm(flagSection.get(key.str), context, true, true), null);
}
entity.safeAdjust(new Mechanism("flag_map", tracker.map, context));
}
if (contains("mechanisms", Map.class)) {
YamlConfiguration mechSection = getConfigurationSection("mechanisms");
Set<StringHolder> strings = mechSection.getKeys(false);
for (StringHolder string : strings) {
ObjectTag obj = CoreUtilities.objectToTagForm(mechSection.get(string.low), context, true, true);
entity.safeAdjust(new Mechanism(string.low, obj, context));
}
}
boolean any = false;
Set<StringHolder> strings = getContents().getKeys(false);
for (StringHolder string : strings) {
if (!nonMechanismKeys.contains(string.low)) {
any = true;
ObjectTag obj = CoreUtilities.objectToTagForm(getContents().get(string.low), context, true, true);
entity.safeAdjust(new Mechanism(string.low, obj, context));
}
}
if (any) {
Deprecations.entityMechanismsFormat.warn(this);
}
if (entity == null || entity.isUnique()) {
return null;
}
entity.setEntityScript(getName());
} catch (Exception e) {
Debug.echoError("Woah! An exception has been called with this entity script!");
Debug.echoError(e);
entity = null;
}
return entity;
}
use of com.denizenscript.denizencore.objects.core.ScriptTag in project Denizen-For-Bukkit by DenizenScript.
the class FormatScriptContainer method getFormattedText.
public String getFormattedText(String textToReplace, NPCTag npc, PlayerTag player) {
String name = npc != null ? npc.getName() : (player != null ? player.getName() : "");
String text = getFormat();
if (text.contains("<text") || text.contains("<name")) {
Deprecations.pseudoTagBases.warn(this);
text = text.replace("<text", "<element[" + EscapeTagBase.escape(textToReplace) + "].unescaped").replace("<name", "<element[" + EscapeTagBase.escape(name) + "].unescaped");
}
BukkitTagContext context = new BukkitTagContext(player, npc, new ScriptTag(this));
context.definitionProvider = new SimpleDefinitionProvider();
context.definitionProvider.addDefinition("text", new ElementTag(textToReplace));
context.definitionProvider.addDefinition("name", new ElementTag(name));
return TagManager.tag(text, context);
}
use of com.denizenscript.denizencore.objects.core.ScriptTag in project Denizen-For-Bukkit by DenizenScript.
the class ItemScriptHelper method registerShapedRecipe.
public void registerShapedRecipe(ItemScriptContainer container, ItemStack item, List<String> recipeList, String internalId, String group) {
for (int n = 0; n < recipeList.size(); n++) {
recipeList.set(n, TagManager.tag(ScriptBuilder.stripLinePrefix(recipeList.get(n)), new BukkitTagContext(null, null, new ScriptTag(container))));
}
List<ItemStack[]> ingredients = new ArrayList<>();
List<Boolean> exacts = new ArrayList<>();
int width = 1;
for (String recipeRow : recipeList) {
String[] elements = recipeRow.split("\\|", 3);
if (width < 3 && elements.length == 3) {
width = 3;
}
if (width < 2 && elements.length >= 2) {
width = 2;
}
for (String element : elements) {
String itemText = element;
boolean isExact = !itemText.startsWith("material:");
if (!isExact) {
itemText = itemText.substring("material:".length());
}
exacts.add(isExact);
ItemStack[] items = textToItemArray(container, itemText, isExact);
if (items == null) {
return;
}
ingredients.add(items);
}
}
NamespacedKey key = new NamespacedKey("denizen", internalId);
ShapedRecipe recipe = new ShapedRecipe(key, item);
recipe.setGroup(group);
String shape1 = "ABC".substring(0, width);
String shape2 = "DEF".substring(0, width);
String shape3 = "GHI".substring(0, width);
String itemChars = shape1 + shape2 + shape3;
if (recipeList.size() == 3) {
recipe = recipe.shape(shape1, shape2, shape3);
} else if (recipeList.size() == 2) {
recipe = recipe.shape(shape1, shape2);
} else {
recipe = recipe.shape(shape1);
}
for (int i = 0; i < ingredients.size(); i++) {
if (ingredients.get(i).length != 0) {
NMSHandler.getItemHelper().setShapedRecipeIngredient(recipe, itemChars.charAt(i), ingredients.get(i), exacts.get(i));
}
}
Bukkit.addRecipe(recipe);
}
use of com.denizenscript.denizencore.objects.core.ScriptTag in project Denizen-For-Bukkit by DenizenScript.
the class ShootCommand method execute.
@Override
public void execute(final ScriptEntry scriptEntry) {
EntityTag originEntity = scriptEntry.getObjectTag("origin_entity");
LocationTag originLocation = scriptEntry.hasObject("origin_location") ? (LocationTag) scriptEntry.getObject("origin_location") : new LocationTag(originEntity.getEyeLocation().add(originEntity.getEyeLocation().getDirection()));
boolean no_rotate = scriptEntry.hasObject("no_rotate") && scriptEntry.getElement("no_rotate").asBoolean();
// If there is no destination set, but there is a shooter, get a point
// in front of the shooter and set it as the destination
final LocationTag destination = scriptEntry.hasObject("destination") ? (LocationTag) scriptEntry.getObject("destination") : (originEntity != null ? new LocationTag(originEntity.getEyeLocation().clone().add(originEntity.getEyeLocation().clone().getDirection().multiply(30))) : (originLocation != null ? new LocationTag(originLocation.clone().add(originLocation.getDirection().multiply(30))) : null));
// TODO: Same as PUSH -- is this the place to do this?
if (destination == null) {
Debug.echoError("No destination specified!");
return;
}
final List<EntityTag> entities = (List<EntityTag>) scriptEntry.getObject("entities");
final ScriptTag script = scriptEntry.getObjectTag("script");
final ElementTag subPath = scriptEntry.getElement("path");
final ListTag definitions = scriptEntry.getObjectTag("definitions");
EntityTag shooter = scriptEntry.getObjectTag("shooter");
ElementTag height = scriptEntry.getElement("height");
ElementTag gravity = scriptEntry.getElement("gravity");
ElementTag speed = scriptEntry.getElement("speed");
ElementTag spread = scriptEntry.getElement("spread");
LocationTag lead = scriptEntry.getObjectTag("lead");
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(), originEntity, originLocation, db("entities", entities), destination, height, gravity, speed, script, subPath, shooter, spread, lead, (no_rotate ? db("no_rotate", "true") : ""), definitions);
}
final ListTag entityList = new ListTag();
if (!no_rotate) {
originLocation = new LocationTag(NMSHandler.getEntityHelper().faceLocation(originLocation, destination));
}
for (EntityTag entity : entities) {
if (!entity.isSpawned() || !no_rotate) {
entity.spawnAt(originLocation);
}
entityList.addObject(entity);
if (entity.isProjectile()) {
if (shooter != null || originEntity != null) {
entity.setShooter(shooter != null ? shooter : originEntity);
}
if (script != null || scriptEntry.shouldWaitFor()) {
arrows.put(entity.getUUID(), null);
}
}
}
scriptEntry.addObject("shot_entities", entityList);
if (entityList.size() == 1) {
scriptEntry.addObject("shot_entity", entityList.getObject(0));
}
if (spread == null) {
Position.mount(Conversion.convertEntities(entities));
}
final EntityTag lastEntity = entities.get(entities.size() - 1);
if (speed == null) {
if (gravity == null) {
gravity = new ElementTag(lastEntity.getEntityType().getGravity());
}
Vector v1 = lastEntity.getLocation().toVector();
Vector v2 = destination.toVector();
Vector v3 = Velocity.calculate(v1, v2, gravity.asDouble(), height.asDouble());
lastEntity.setVelocity(v3);
} else if (lead == null) {
Vector relative = destination.clone().subtract(originLocation).toVector();
lastEntity.setVelocity(relative.normalize().multiply(speed.asDouble()));
} else {
double g = 20;
double v = speed.asDouble();
Vector relative = destination.clone().subtract(originLocation).toVector();
double testAng = Velocity.launchAngle(originLocation, destination.toVector(), v, relative.getY(), g);
double hangTime = Velocity.hangtime(testAng, v, relative.getY(), g);
Vector to = destination.clone().add(lead.clone().multiply(hangTime)).toVector();
relative = to.clone().subtract(originLocation.toVector());
double dist = Math.sqrt(relative.getX() * relative.getX() + relative.getZ() * relative.getZ());
if (dist == 0) {
dist = 0.1d;
}
testAng = Velocity.launchAngle(originLocation, to, v, relative.getY(), g);
relative.setY(Math.tan(testAng) * dist);
relative = relative.normalize();
v = v + (1.188 * Math.pow(hangTime, 2));
relative = relative.multiply(v / 20.0d);
lastEntity.setVelocity(relative);
}
if (spread != null) {
Vector base = lastEntity.getVelocity().clone();
float sf = spread.asFloat();
for (EntityTag entity : entities) {
Vector newvel = Velocity.spread(base, (CoreUtilities.getRandom().nextDouble() > 0.5f ? 1 : -1) * Math.toRadians(CoreUtilities.getRandom().nextDouble() * sf), (CoreUtilities.getRandom().nextDouble() > 0.5f ? 1 : -1) * Math.toRadians(CoreUtilities.getRandom().nextDouble() * sf));
entity.setVelocity(newvel);
}
}
final LocationTag start = new LocationTag(lastEntity.getLocation());
// A task used to trigger a script if the entity is no longer
// being shot, when the script argument is used
BukkitRunnable task = new BukkitRunnable() {
boolean flying = true;
LocationTag lastLocation = null;
Vector lastVelocity = null;
public void run() {
// If the entity is no longer spawned, stop the task
if (!lastEntity.isSpawned()) {
if (Debug.verbose) {
Debug.log("Shoot ended because entity not spawned");
}
flying = false;
} else // the air, stop the task
if (lastLocation != null && lastVelocity != null && !(lastEntity.getBukkitEntity() instanceof Projectile)) {
if (lastLocation.getWorld() != lastEntity.getBukkitEntity().getWorld() || (lastLocation.distanceSquared(lastEntity.getBukkitEntity().getLocation()) < 0.1 && lastVelocity.distanceSquared(lastEntity.getBukkitEntity().getVelocity()) < 0.1)) {
if (Debug.verbose) {
Debug.log("Shoot ended because distances short - locations: " + (lastLocation.distanceSquared(lastEntity.getBukkitEntity().getLocation())) + ", velocity: " + (lastVelocity.distanceSquared(lastEntity.getBukkitEntity().getVelocity()) < 0.1));
}
flying = false;
}
}
if (!arrows.containsKey(lastEntity.getUUID()) || arrows.get(lastEntity.getUUID()) != null) {
if (Debug.verbose) {
Debug.log("Shoot ended because uuid was updated (hit entity?)");
}
flying = false;
}
// are met
if (!flying) {
this.cancel();
ListTag hitEntities = new ListTag();
for (EntityTag entity : entities) {
if (arrows.containsKey(entity.getUUID())) {
EntityTag hit = arrows.get(entity.getUUID());
arrows.remove(entity.getUUID());
if (hit != null) {
hitEntities.addObject(hit);
}
}
}
if (lastLocation == null) {
lastLocation = start;
}
scriptEntry.addObject("location", new LocationTag(lastLocation));
scriptEntry.addObject("hit_entities", hitEntities);
if (script != null) {
Consumer<ScriptQueue> configure = (queue) -> {
queue.addDefinition("location", new LocationTag(lastLocation));
queue.addDefinition("shot_entities", entityList);
queue.addDefinition("last_entity", lastEntity);
queue.addDefinition("hit_entities", hitEntities);
};
ScriptUtilities.createAndStartQueue(script.getContainer(), subPath == null ? null : subPath.asString(), scriptEntry.entryData, null, configure, null, null, definitions, scriptEntry);
}
scriptEntry.setFinished(true);
} else {
// Record its position in case the entity dies
lastLocation = lastEntity.getLocation();
lastVelocity = lastEntity.getVelocity();
}
}
};
if (script != null || scriptEntry.shouldWaitFor()) {
task.runTaskTimer(Denizen.getInstance(), 1, 2);
}
}
Aggregations