Add player animation system!

- Hooks into ModelRenderer by wrapping it in an extended version that allows modification of angles after the model has set them
- Is compatible with pretty much everything, yay (even modded armour!)
- Adds property overrides to ItemWand so that gets animated too
- Adds a system for generating override models from a template at runtime so I don't have to duplicate all the wand models
- Tweaks particles and ray spells so they line up with the end of the newly-animated wand
- Fixes a long-standing bug where wand usage actions would stop immediately for all non-continuous spells
This commit is contained in:
Electroblob77
2020-05-09 20:17:15 +01:00
parent cf38a16f49
commit be250e218e
146 changed files with 1531 additions and 262 deletions
@@ -3,6 +3,8 @@ package electroblob.wizardry.client;
import electroblob.wizardry.CommonProxy;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.block.BlockBookshelf;
import electroblob.wizardry.client.animation.ActionAnimation;
import electroblob.wizardry.client.animation.PlayerAnimator;
import electroblob.wizardry.client.audio.MovingSoundEntity;
import electroblob.wizardry.client.audio.SoundLoop;
import electroblob.wizardry.client.audio.SoundLoopSpell;
@@ -140,7 +142,7 @@ public class ClientProxy extends CommonProxy {
mixedFontRenderer = new MixedFontRenderer(Minecraft.getMinecraft().gameSettings, new ResourceLocation("textures/font/ascii.png"),
Minecraft.getMinecraft().renderEngine, false);
}
@Override
public void registerResourceReloadListeners(){
IResourceManager manager = Minecraft.getMinecraft().getResourceManager();
@@ -166,7 +168,7 @@ public class ClientProxy extends CommonProxy {
public void setToNumberSliderEntry(Property property){
property.setConfigEntryClass(NumberSliderEntry.class);
}
@Override
public void setToHUDChooserEntry(Property property){
property.setConfigEntryClass(SpellHUDSkinChooserEntry.class);
@@ -182,11 +184,16 @@ public class ClientProxy extends CommonProxy {
return Minecraft.getMinecraft().world;
}
@Override
public boolean isFirstPerson(Entity entity){
return entity == Minecraft.getMinecraft().getRenderViewEntity() && Minecraft.getMinecraft().gameSettings.thirdPersonView == 0;
}
@Override
public void playMovingSound(Entity entity, SoundEvent sound, SoundCategory category, float volume, float pitch, boolean repeat){
Minecraft.getMinecraft().getSoundHandler().playSound(new MovingSoundEntity<>(entity, sound, category, volume, pitch, repeat));
}
@Override
public void playSpellSoundLoop(EntityLivingBase entity, Spell spell, SoundEvent start, SoundEvent loop, SoundEvent end, SoundCategory category, float volume, float pitch){
SoundLoop.addLoop(new SoundLoopSpell.SoundLoopSpellEntity(start, loop, end, spell, entity, volume, pitch));
@@ -363,7 +370,7 @@ public class ClientProxy extends CommonProxy {
ParticleWizardry.registerParticle(Type.SUMMON, ParticleSummon::new);
ParticleWizardry.registerParticle(Type.VINE, ParticleVine::new);
}
@Override
public ParticleWizardry createParticle(ResourceLocation type, World world, double x, double y, double z){
IWizardryParticleFactory factory = factories.get(type);
@@ -483,36 +490,36 @@ public class ClientProxy extends CommonProxy {
Wizardry.logger.warn("Recieved a PacketNPCCastSpell, but the caster ID was not the ID of an EntityLiving");
}
}
@Override
public void handleDispenserCastSpellPacket(PacketDispenserCastSpell.Message message){
World world = Minecraft.getMinecraft().world;
if(world.getTileEntity(message.pos) instanceof TileEntityDispenser){ // Should always be true
Spell spell = Spell.byNetworkID(message.spellID);
spell.cast(world, message.x, message.y, message.z, message.direction, 0, -1, message.modifiers);
// No need to check if the spell succeeded, because the packet is only ever sent when it succeeds.
MinecraftForge.EVENT_BUS.post(new SpellCastEvent.Post(Source.DISPENSER, spell, world, message.x, message.y,
message.z, message.direction, message.modifiers));
if(spell.isContinuous || spell instanceof None){
DispenserCastingData data = DispenserCastingData.get((TileEntityDispenser)world.getTileEntity(message.pos));
if(spell.isContinuous){
data.startCasting(spell, message.x, message.y, message.z, message.duration, message.modifiers);
}else{
data.stopCasting();
}
}
}else{
Wizardry.logger.warn("Recieved a PacketDispenserCastSpell, but no tileEntity was found at the supplied location.");
}
}
@Override
@@ -682,6 +689,12 @@ public class ClientProxy extends CommonProxy {
LayerFrost.initialiseLayers();
}
@Override
public void initialiseAnimations(){
PlayerAnimator.init();
ActionAnimation.register();
}
@Override
public void registerRenderers(){
@@ -0,0 +1,154 @@
package electroblob.wizardry.client.animation;
import electroblob.wizardry.data.WizardData;
import electroblob.wizardry.item.SpellActions;
import electroblob.wizardry.spell.Grapple;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
/**
* An animation that is associated with a particular {@link net.minecraft.item.EnumAction}. This animation will display
* when a player is using an item with that action.
* @author Electroblob
* @since Wizardry 4.3
* @see electroblob.wizardry.item.SpellActions
*/
public abstract class ActionAnimation extends Animation {
private final EnumAction action;
public ActionAnimation(EnumAction action){
super(action.name());
this.action = action;
}
@Override
public boolean shouldDisplay(EntityPlayer player, boolean firstPerson){
return !firstPerson && player.getItemInUseCount() > 0 && player.getActiveItemStack().getItemUseAction() == action;
}
/** Called from the client proxy to register all of wizardry's action animations. */
public static void register(){
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.POINT){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
// Something (probably some sort of race condition) causes getActiveItemStack to sometimes be wrong
if(player.getActiveItemStack() != player.getHeldItem(player.getActiveHand())) return;
EnumHandSide side = WizardryUtilities.getSideForHand(player, player.getActiveHand());
float pitch = (float)Math.toRadians(player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * partialTicks);
float yaw = (float)Math.toRadians(player.prevRotationYawHead + (player.rotationYawHead - player.prevRotationYawHead) * partialTicks)
- (float)Math.toRadians(player.prevRenderYawOffset + (player.renderYawOffset - player.prevRenderYawOffset) * partialTicks);
float x = -((float)Math.PI / 2) + pitch + 0.2f;
float y = (side == EnumHandSide.RIGHT ? -0.25f : 0.25f) + yaw;
ModelRendererExtended arm = (ModelRendererExtended)getArmForSide(model, side);
arm.setRotation(x, y, 0);
}
});
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.POINT_UP){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
if(player.getActiveItemStack() != player.getHeldItem(player.getActiveHand())) return;
EnumHandSide side = WizardryUtilities.getSideForHand(player, player.getActiveHand());
ModelRendererExtended arm = (ModelRendererExtended)getArmForSide(model, side);
arm.addRotation(-2.2f, side == EnumHandSide.RIGHT ? 0.2f : -0.2f, 0);
}
});
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.POINT_DOWN){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
float tick = player.getItemInUseMaxCount() + partialTicks; // It's not the "max" use count at all!
float y = Math.min(0.4f + tick * 0.05f, 0.7f);
EnumHandSide side = WizardryUtilities.getSideForHand(player, player.getActiveHand());
ModelRendererExtended arm = (ModelRendererExtended)getArmForSide(model, side);
arm.addRotation(-0.2f, side == EnumHandSide.RIGHT ? y : -y, 0);
}
});
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.SUMMON){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
float tick = player.getItemInUseMaxCount() + partialTicks; // It's not the "max" use count at all!
float x = -Math.min(0.4f + tick * 0.2f, 2f);
((ModelRendererExtended)getArmForSide(model, EnumHandSide.RIGHT)).addRotation(x, 1.2f, 0);
((ModelRendererExtended)getArmForSide(model, EnumHandSide.LEFT)).addRotation(x, -1.2f, 0);
}
});
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.GRAPPLE){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
WizardData data = WizardData.get(player);
RayTraceResult hit = data.getVariable(Grapple.TARGET_KEY);
if(hit == null || hit.typeOfHit == RayTraceResult.Type.MISS) return;
Vec3d target = hit.hitVec;
if(hit.entityHit instanceof EntityLivingBase){
// If the target is an entity, we need to use the entity's centre rather than the original hit position
// because the entity will have moved!
target = new Vec3d(hit.entityHit.posX, hit.entityHit.getEntityBoundingBox().minY + hit.entityHit.height/2, hit.entityHit.posZ);
}
EnumHandSide side = WizardryUtilities.getSideForHand(player, player.getActiveHand());
ModelRendererExtended arm = (ModelRendererExtended)getArmForSide(model, side);
Vec3d direction = target.subtract(player.getPositionEyes(partialTicks));
float yaw = player.prevRenderYawOffset + (player.renderYawOffset - player.prevRenderYawOffset) * partialTicks;
float pitch = (float)MathHelper.atan2(MathHelper.sqrt(direction.x*direction.x + direction.z*direction.z), direction.y);
float x = pitch - (float)Math.PI * 0.9f;
float y = -(float)Math.toRadians(yaw) - (float)MathHelper.atan2(direction.x, direction.z);
y += (side == EnumHandSide.RIGHT ? -0.25f : 0.25f);
if(Math.abs(pitch) < 0.2f) y = arm.rotateAngleY;
arm.setRotation(x, y, 0);
}
});
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.IMBUE){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
float tick = player.getItemInUseMaxCount() + partialTicks; // It's not the "max" use count at all!
float z = Math.max(1.5f - tick * 0.1f, 0.8f);
EnumHandSide side = WizardryUtilities.getSideForHand(player, player.getActiveHand());
ModelRendererExtended arm = (ModelRendererExtended)getArmForSide(model, side);
arm.addRotation(-1.2f, side == EnumHandSide.RIGHT ? -0.2f : 0.2f, side == EnumHandSide.RIGHT ? z : -z);
if(!player.getHeldItem(WizardryUtilities.getHandForSide(player, side.opposite())).isEmpty()){
((ModelRendererExtended)getArmForSide(model, side.opposite())).addRotation(-0.8f, side == EnumHandSide.LEFT ? 0.3f : -0.3f, 0);
}
}
});
PlayerAnimator.registerAnimation(new ActionAnimation(SpellActions.THRUST){
@Override
public void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson){
if(player.getActiveItemStack() != player.getHeldItem(player.getActiveHand())) return;
EnumHandSide side = WizardryUtilities.getSideForHand(player, player.getActiveHand());
ModelRendererExtended arm = (ModelRendererExtended)getArmForSide(model, side);
float y = side == EnumHandSide.RIGHT ? -0.6f : 0.6f;
arm.addRotation(-1.2f, y, 0);
if(player.getHeldItem(WizardryUtilities.getHandForSide(player, side.opposite())).isEmpty()){
ModelRendererExtended otherArm = (ModelRendererExtended)getArmForSide(model, side.opposite());
otherArm.setRotation(arm.rotateAngleX - 1.2f, -arm.rotateAngleY - y, otherArm.rotateAngleZ);
}
}
});
}
}
@@ -0,0 +1,77 @@
package electroblob.wizardry.client.animation;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumHandSide;
/**
* Represents a player animation. Use one of the predefined subclasses below for common animation types, or extend this
* class directly to define a completely custom animation. Register instances of this class using
* {@link PlayerAnimator#registerAnimation(Animation)}.
* @author Electroblob
* @since Wizardry 4.3
* @see ActionAnimation
*/
public abstract class Animation {
private final String name;
public Animation(String name){
this.name = name;
}
/** Returns the name of this animation, currently only used for warning messages / debugging. */
public String getName(){
return name;
}
/**
* Returns whether this animation should be displayed for the given player. <i>Note that if two registered
* animations have overlapping conditions, both will attempt to display simultaneously, so if they both animate the
* same model part, that part may not behave as expected.</i>
* @param player The player being animated
* @param firstPerson True if the player being animated is the local client player, and they are in first-person
* view. In first-person, animations are only useful for animating the player's empty hand.
* @return True if the animation should be displayed, false if not.
*/
public abstract boolean shouldDisplay(EntityPlayer player, boolean firstPerson);
/**
* Sets the rotation of the model parts for this animation. This method is called every time the player is rendered
* when {@link Animation#shouldDisplay(EntityPlayer, boolean)} returns true.
* @param player The player being animated
* @param model The model to animate. All of the standard {@link ModelBiped} parts will already be wrapped and may
* be safely cast to {@code ModelRendererExtended} in order to override the rotations set by the model
* itself - see {@link ModelRendererExtended ModelRendererExtended} for details.
* @param partialTicks The current partial tick time
* @param firstPerson True if the player being animated is the local client player, and they are in first-person
* view. In first-person, animations are only useful for animating the player's empty hand.
*/
public abstract void setRotationAngles(EntityPlayer player, ModelBiped model, float partialTicks, boolean firstPerson);
/**
* Returns whether the boxes that form the second layer of the player's skin (for models that are instances of
* {@link net.minecraft.client.model.ModelPlayer ModelPlayer}) should automatically be set to the same angles as
* their corresponding first-layer parts.
* @param player The player being rendered, for reference
* @param firstPerson True if the player being animated is the local client player, and they are in first-person
* view. In first-person, animations are only useful for animating the player's empty hand.
* @return True to let {@link PlayerAnimator} auto-rotate the second skin layer, false to rotate them manually.
*/
public boolean autoRotateSecondLayer(EntityPlayer player, boolean firstPerson){
return true;
}
/**
* Returns the arm of the given model corresponding to the given side. Function is identical to the method of the
* same name in {@link ModelBiped}.
* @param model The model to get the arm of
* @param side The {@link EnumHandSide} to return the arm for
* @return The {@link ModelRenderer} corresponding to the given arm
*/
public static ModelRenderer getArmForSide(ModelBiped model, EnumHandSide side){
return side == EnumHandSide.LEFT ? model.bipedLeftArm : model.bipedRightArm;
}
}
@@ -0,0 +1,177 @@
package electroblob.wizardry.client.animation;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelPlayer;
import net.minecraft.client.model.ModelRenderer;
/**
* A wrapper around {@link ModelRenderer} which can be swapped into models to allow render pre/post events to
* circumvent {@code ModelBase.setRotationAngles(...)} and set model part rotations themselves. Instances of this class
* keep a reference to the original {@code ModelRenderer} and delegate all the actual rendering to it.
* <p></p>
* {@link PlayerAnimator PlayerAnimator} does all the necessary setup with this
* class for player animations. It is also possible to set up custom animations for non-player entities with this class,
* see {@link ModelRendererExtended#wrap(ModelBiped)} and {@link ModelRendererExtended#wrap(ModelBase, ModelRenderer)}.
* @author Electroblob
* @since Wizardry 4.3
*/
public class ModelRendererExtended extends ModelRenderer {
// We probably could have copied all the fields over instead, but this way if anyone else modifies the boxes we
// won't overwrite their changes
// This way also avoids reflection because we don't need to copy private fields, which is better for performance
private ModelRenderer delegate;
private float actualRotationX;
private float actualRotationY;
private float actualRotationZ;
private float extraRotationX;
private float extraRotationY;
private float extraRotationZ;
private ModelRendererExtended(ModelBase baseModel, ModelRenderer delegate){
super(baseModel, delegate.boxName);
this.delegate = delegate;
// Copy over any public fields that might get changed
this.textureWidth = delegate.textureWidth;
this.textureHeight = delegate.textureHeight;
this.showModel = delegate.showModel;
this.isHidden = delegate.isHidden;
this.rotationPointX = delegate.rotationPointX;
this.rotationPointY = delegate.rotationPointY;
this.rotationPointZ = delegate.rotationPointZ;
this.resetRotation();
}
// Static initialisers
/**
* Replaces the given part of the given {@link ModelBase} with a new {@code ModelRendererExtended} that wraps the
* original part. This method takes care of modifying the model's box list, but <b>is unable to change any
* individual {@link ModelRenderer} fields</b> - this method instead returns the resulting
* {@code ModelRendererExtended} to be assigned to the appropriate field.
* @param model The model whose part is to be wrapped
* @param box The part of the model to wrap, must belong to the above model
* @return The resulting wrapped model part, this should be assigned to the appropriate part field in the model. If
* the given model part was already wrapped, this method simply returns it unchanged.
* @throws IllegalArgumentException if the given box does not belong to the given model
*/
public static ModelRendererExtended wrap(ModelBase model, ModelRenderer box){
if(box instanceof ModelRendererExtended) return (ModelRendererExtended)box; // Ignore already-wrapped parts
ModelRendererExtended wrapper = new ModelRendererExtended(model, box);
int index = model.boxList.indexOf(box);
if(index < 0) throw new IllegalArgumentException(String.format("The given ModelRenderer %s does not belong to the given model %s", model, box));
model.boxList.set(index, wrapper); // I doubt the order matters but we may as well put it at the same index
return wrapper;
}
/**
* Replaces the given {@link ModelBiped}'s parts with new {@code ModelRendererExtended} versions that wrap the
* original parts. If the given model is a {@link ModelPlayer}, the extra boxes for player skin overlays will also
* be wrapped.
*/
public static void wrap(ModelBiped model){
// MMmmmmmm wraps
model.bipedHead = wrap(model, model.bipedHead);
model.bipedBody = wrap(model, model.bipedBody);
model.bipedRightArm = wrap(model, model.bipedRightArm);
model.bipedLeftArm = wrap(model, model.bipedLeftArm);
model.bipedRightLeg = wrap(model, model.bipedRightLeg);
model.bipedLeftLeg = wrap(model, model.bipedLeftLeg);
model.bipedHeadwear = wrap(model, model.bipedHeadwear);
if(model instanceof ModelPlayer){
((ModelPlayer)model).bipedBodyWear = wrap(model, ((ModelPlayer)model).bipedBodyWear);
((ModelPlayer)model).bipedRightArmwear = wrap(model, ((ModelPlayer)model).bipedRightArmwear);
((ModelPlayer)model).bipedLeftArmwear = wrap(model, ((ModelPlayer)model).bipedLeftArmwear);
((ModelPlayer)model).bipedRightLegwear = wrap(model, ((ModelPlayer)model).bipedRightLegwear);
((ModelPlayer)model).bipedLeftLegwear = wrap(model, ((ModelPlayer)model).bipedLeftLegwear);
}
}
/** Resets the rotation of this model part to the angle set by the parent model. */
public void resetRotation(){
this.actualRotationX = Float.NaN;
this.actualRotationY = Float.NaN;
this.actualRotationZ = Float.NaN;
this.extraRotationX = 0;
this.extraRotationY = 0;
this.extraRotationZ = 0;
}
/** Sets the rotation of this model part, which will overwrite the angle set by the parent model. */
public void setRotation(float x, float y, float z){
this.actualRotationX = x;
this.actualRotationY = y;
this.actualRotationZ = z;
}
/** Sets the extra rotation of this model part, which will be added onto the angle set by the parent model. */
public void addRotation(float x, float y, float z){
this.extraRotationX = x;
this.extraRotationY = y;
this.extraRotationZ = z;
}
/** Sets the rotation of this model part to the same values as the given box. */
public void setRotationTo(ModelRendererExtended box){
this.actualRotationX = box.actualRotationX;
this.actualRotationY = box.actualRotationY;
this.actualRotationZ = box.actualRotationZ;
this.extraRotationX = box.extraRotationX;
this.extraRotationY = box.extraRotationY;
this.extraRotationZ = box.extraRotationZ;
}
// Delegate rendering, but fiddle with the angles first
@Override
public void render(float scale){
// Need to copy these over each time in case they were changed
delegate.showModel = this.showModel;
delegate.isHidden = this.isHidden;
delegate.rotationPointX = this.rotationPointX;
delegate.rotationPointY = this.rotationPointY;
delegate.rotationPointZ = this.rotationPointZ;
if(!Float.isNaN(actualRotationX) && !Float.isNaN(actualRotationY) && !Float.isNaN(actualRotationZ)){
delegate.rotateAngleX = actualRotationX;
delegate.rotateAngleY = actualRotationY;
delegate.rotateAngleZ = actualRotationZ;
}else{
delegate.rotateAngleX = this.rotateAngleX + extraRotationX;
delegate.rotateAngleY = this.rotateAngleY + extraRotationY;
delegate.rotateAngleZ = this.rotateAngleZ + extraRotationZ;
}
delegate.render(scale);
}
// Delegate all other methods
@Override
public void addChild(ModelRenderer renderer){
delegate.addChild(renderer);
}
@Override
public void renderWithRotation(float scale){
delegate.renderWithRotation(scale);
}
@Override
public void postRender(float scale){
// TODO: It may just be easier to hardcode the item rotation part of the animation as well
// Exactly the same setup as above, just add item rotation/translation fields and setters
// float angle = 1;
// float radius = 10;
// delegate.rotationPointY -= radius * MathHelper.cos(angle);
// delegate.rotationPointZ -= radius * MathHelper.sin(angle);
// delegate.rotateAngleX += angle;
delegate.postRender(scale);
}
}
@@ -0,0 +1,213 @@
package electroblob.wizardry.client.animation;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.item.SpellActions;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelPlayer;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.RenderPlayer;
import net.minecraft.client.renderer.entity.layers.LayerBipedArmor;
import net.minecraft.client.renderer.entity.layers.LayerRenderer;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderSpecificHandEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Handles the setup and rendering events for custom player animations, as well as registering of animations. Addons
* can also register their own animations here, see {@link PlayerAnimator#registerAnimation(Animation)}.
* @author Electroblob
* @since Wizardry 4.3
* @see electroblob.wizardry.item.SpellActions SpellActions
*/
@Mod.EventBusSubscriber(Side.CLIENT)
public class PlayerAnimator {
// TODO: Attempt to extend this to all bipeds
private static final List<Animation> animations = new ArrayList<>();
/** Stores all registered layer renderers for lazy-loading of armour models later. */
private static final Map<RenderPlayer, List<LayerRenderer<? extends EntityLivingBase>>> playerLayers = new HashMap<>();
/** Stores the main model for each renderer plus all models for registered layer renderers. */
private static final Map<RenderPlayer, List<ModelBiped>> playerLayerModels = new HashMap<>();
/** Reflected into {@link RenderLivingBase}{@code #layerRenderers}. */
private static final Field layerRenderers;
static {
layerRenderers = ObfuscationReflectionHelper.findField(RenderLivingBase.class, "field_177097_h");
}
/**
* Registers a new player animation. This method should be called from the {@code init()} phase via a client proxy.
* @param animation The animation to register
*/
// N.B. This can (and will) be called before PlayerAnimator#init() is called
public static void registerAnimation(Animation animation){
if(animations.contains(animation)){
Wizardry.logger.warn("Animation {} is already registered!", animation.getName());
}else{
animations.add(animation);
}
}
// TODO: Figure out if calling this from postInit ensures we catch all the layers, and lazy-load it if not
@SuppressWarnings("unchecked")
public static void init(){
for(RenderPlayer renderer : Minecraft.getMinecraft().getRenderManager().getSkinMap().values()){
List<ModelBiped> models = new ArrayList<>();
ModelRendererExtended.wrap(renderer.getMainModel());
models.add(renderer.getMainModel());
try {
List<LayerRenderer<? extends EntityLivingBase>> layers = (List<LayerRenderer<? extends EntityLivingBase>>)layerRenderers.get(renderer);
playerLayers.put(renderer, layers);
for(LayerRenderer<?> layer : layers){
for(Field field : WizardryUtilities.getAllFields(layer.getClass())){
field.setAccessible(true);
// If your layer model doesn't extend ModelBiped, you DESERVE to be incompatible!
// (Just kidding... there's nothing I can do about it anyway)
if(field.get(layer) instanceof ModelBiped){
ModelBiped model = (ModelBiped)field.get(layer);
ModelRendererExtended.wrap(model);
models.add(model);
}
}
}
}catch(IllegalAccessException e){
Wizardry.logger.error("Error during reflective access of render layers: ", e);
}
playerLayerModels.put(renderer, models);
}
}
private static void updateModels(EntityPlayer player, Render<?> renderer, float partialTicks, boolean firstPerson){
// Biped armour is special because of Forge's armour item render hook
// This needs to be lazy-loaded because we need access to an actual item
for(LayerRenderer<? extends EntityLivingBase> layer : playerLayers.get(renderer)){
if(layer instanceof LayerBipedArmor){
for(EntityEquipmentSlot slot : WizardryUtilities.ARMOUR_SLOTS){
ItemStack armour = player.getItemStackFromSlot(slot);
ModelBiped model = ForgeHooksClient.getArmorModel(player, armour, slot, ((LayerBipedArmor)layer).getModelFromSlot(slot));
List<ModelBiped> models = playerLayerModels.get(renderer);
if(!models.contains(model)){
models.add(model);
ModelRendererExtended.wrap(model);
}
}
}
}
boolean flag = false;
for(Animation animation : animations){
boolean autoRotateSecondLayer = animation.autoRotateSecondLayer(player, firstPerson);
if(animation.shouldDisplay(player, firstPerson)){
flag = true;
for(ModelBiped model : playerLayerModels.get(renderer)){
animation.setRotationAngles(player, model, partialTicks, firstPerson);
if(autoRotateSecondLayer && model instanceof ModelPlayer){
alignSecondLayer((ModelPlayer)model);
}
}
}
}
if(!flag){
for(ModelBiped model : playerLayerModels.get(renderer)){
for(ModelRenderer box : model.boxList){ // For ModelPlayer, this will include the second layer
// Some models have extra boxes, they (probably) don't need wrapping but we need this check!
if(box instanceof ModelRendererExtended){
((ModelRendererExtended)box).resetRotation();
}
}
}
}
}
/** Rotates the second layer boxes of the given (wrapped) player model to match the first layer. */
public static void alignSecondLayer(ModelPlayer model){
((ModelRendererExtended)model.bipedBodyWear) .setRotationTo((ModelRendererExtended)model.bipedBody);
((ModelRendererExtended)model.bipedRightArmwear).setRotationTo((ModelRendererExtended)model.bipedRightArm);
((ModelRendererExtended)model.bipedLeftArmwear) .setRotationTo((ModelRendererExtended)model.bipedLeftArm);
((ModelRendererExtended)model.bipedRightLegwear).setRotationTo((ModelRendererExtended)model.bipedBody);
((ModelRendererExtended)model.bipedLeftLegwear) .setRotationTo((ModelRendererExtended)model.bipedBody);
}
@SubscribeEvent
public static void onRenderHandEvent(RenderSpecificHandEvent event){
AbstractClientPlayer player = Minecraft.getMinecraft().player;
EnumAction action = event.getItemStack().getItemUseAction();
if(player.isHandActive() && player.getActiveHand() == event.getHand() && SpellActions.getSpellActions().contains(action)){
// Minecraft's item renderer helpfully doesn't have a default case for the usage action so it doesn't do any
// transformations at all (which is VERY ANNOYING!) - the following lines are from ItemRenderer#transformSideFirstPerson
int i = (player.getPrimaryHand() == EnumHandSide.RIGHT) == (event.getHand() == EnumHand.MAIN_HAND) ? 1 : -1;
GlStateManager.translate((float)i * 0.56F, -0.52F + event.getEquipProgress() * -0.6F, -0.72F);
}
updateModels(player, Minecraft.getMinecraft().getRenderManager().getEntityRenderObject(player), event.getPartialTicks(), true);
}
@SubscribeEvent
public static void onRenderPlayerPreEvent(RenderPlayerEvent.Pre event){
// boolean firstPerson = event.getEntityPlayer() == Minecraft.getMinecraft().player
// && Minecraft.getMinecraft().gameSettings.thirdPersonView == 0;
updateModels(event.getEntityPlayer(), event.getRenderer(), event.getPartialRenderTick(), false);
}
// @SubscribeEvent
// public static void onRenderPlayerPostEvent(RenderPlayerEvent.Post event){
// TODO: Would we ever need to unwrap the models?
// }
}
@@ -0,0 +1,163 @@
package electroblob.wizardry.client.model;
import com.google.common.collect.ImmutableMap;
import electroblob.wizardry.Wizardry;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.*;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nullable;
import javax.vecmath.Matrix4f;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A special type of model that generates override models dynamically. This allows the same overrides to be applied to
* multiple item models without needing an override version of each one just to point to a texture.
* <p></p>
* To use this system in a model file:<p></p>
* 1. Make a base model file and define the item overrides in it. <b>This model must be placed in the folder
* {@code models/item/override_generators}</b> (unfortunately the folder has to be predefined, see below).<br>
* 2. Make the model files your overrides point to. These should define everything about the model except textures.<br>
* 3. In each model that should generate overrides dynamically, define a single override that points to the location of
* the model from step 1 (the predicate doesn't matter).<br>
* <p></p>
* It is advisable to make the parent of the override model (from step 2) the same as the parent of the model to
* be overridden, so that they share any necessary properties and texture variables. For example, both
* {@code ebwizardry:item/magic_wand.json} and {@code ebwizardry:item/wand_point.json} have {@code item/handheld} as
* their parent. The override model will reference the textures in the original model, so if the override defines a
* face with the texture {@code "#face"}, the texture used will be the file associated with {@code "face"} in the
* original model. For simple models, this will just be the standard {@code "layer0"}.
* @since Wizardry 4.3
* @author Electroblob
*/
// Okay, it's not *that* bad if you only have one override, but imagine having to duplicate every single wand model 5
// times if we wanted 5 animations...
// The nice thing is resource packs don't lose any flexibility this way, they can still redefine the models themselves
// and specify custom models for the overrides if they want, or they can keep using this system - in fact, they GAIN
// flexibility because they can also overwrite the base wand.json model and specify global overrides too
@Mod.EventBusSubscriber(Side.CLIENT)
public class BakedModelGenerateOverrides implements IBakedModel {
// I tried having this as a prefix that gets removed at runtime, which worked fine but it spammed the log with
// errors because the prefixed file doesn't actually exist, so even though it's never used the game still complains
private static final String OVERRIDE_GENERATORS = "override_generators";
private final IBakedModel delegate;
private final ItemOverrideList overrides;
public BakedModelGenerateOverrides(IBakedModel delegate, ItemOverrideList overrides){
this.delegate = delegate;
this.overrides = overrides;
}
@Override
public ItemOverrideList getOverrides(){
return overrides; // The only thing that's not delegated
}
// Delegate everything else
@Override
public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand){
return delegate.getQuads(state, side, rand);
}
@Override
public boolean isAmbientOcclusion(){
return delegate.isAmbientOcclusion();
}
@Override
public boolean isGui3d(){
return delegate.isGui3d();
}
@Override
public boolean isBuiltInRenderer(){
return delegate.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getParticleTexture(){
return delegate.getParticleTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms(){
return delegate.getItemCameraTransforms();
}
@Override
public boolean isAmbientOcclusion(IBlockState state){
return delegate.isAmbientOcclusion(state);
}
@Override
public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType){
return delegate.handlePerspective(cameraTransformType);
}
// Baking
@SubscribeEvent
public static void bake(ModelBakeEvent event){
for(ModelResourceLocation location : event.getModelRegistry().getKeys()){
IBakedModel original = event.getModelRegistry().getObject(location);
if(original != null){
original.getOverrides().getOverrides().stream().map(ItemOverride::getLocation)
.filter(l -> l.getPath().contains(OVERRIDE_GENERATORS)).findFirst()
.ifPresent(l -> event.getModelRegistry().putObject(location,
substituteWandModel(event.getModelManager(), location, original, l)));
}
}
}
// We have to use ModelBakeEvent for this because we need the original model to be baked with the vanilla system
private static IBakedModel substituteWandModel(ModelManager modelManager, ModelResourceLocation location, IBakedModel original, ResourceLocation overrideLocation){
try {
IModel unbakedOriginal = ModelLoaderRegistry.getModel(location);
IModel referenceModel = ModelLoaderRegistry.getModel(overrideLocation);
ModelBlock vanillaOriginal = unbakedOriginal.asVanillaModel().orElse(null);
ModelBlock vanillaRefModel = referenceModel.asVanillaModel().orElse(null);
if(vanillaOriginal != null && vanillaRefModel != null){
// So... many... data structures...
List<ItemOverride> overrides = vanillaRefModel.getOverrides();
Map<ResourceLocation, IBakedModel> replacementMap = new HashMap<>();
for(ItemOverride override : overrides){
IModel replacement = ModelLoaderRegistry.getModel(override.getLocation()).retexture(ImmutableMap.copyOf(vanillaOriginal.textures));
replacementMap.put(override.getLocation(), replacement.bake(unbakedOriginal.getDefaultState(), DefaultVertexFormats.ITEM, ModelLoader.defaultTextureGetter()));
}
ItemOverrideListMapped overrideList = new ItemOverrideListMapped(overrides, replacementMap);
return new BakedModelGenerateOverrides(original, overrideList);
}
}catch(Exception exception){
Wizardry.logger.error("Error baking item display override models: ", exception);
}
return modelManager.getMissingModel();
}
}
@@ -0,0 +1,42 @@
package electroblob.wizardry.client.model;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemOverride;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
/** A version of {@link ItemOverrideList} that uses a predefined map to substitute a specific baked model depending on
* the location the currently-applicable override points to. */
public class ItemOverrideListMapped extends ItemOverrideList {
private final Map<ResourceLocation, IBakedModel> replacementMap;
public ItemOverrideListMapped(List<ItemOverride> overrides, Map<ResourceLocation, IBakedModel> replacementMap){
super(overrides);
this.replacementMap = ImmutableMap.copyOf(replacementMap);
}
@Override
public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity){
if(!stack.isEmpty() && stack.getItem().hasCustomProperties()){
// Get the location the original override points to...
ResourceLocation location = applyOverride(stack, world, entity); // I wonder why this is deprecated?
if(location != null){
return replacementMap.get(location); // ... then substitute in the corresponding generated model
}
}
return originalModel;
}
}
@@ -308,11 +308,11 @@ public final class WizardryModels {
if(location.getNamespace().equals(Wizardry.MODID)){
IBakedModel original = event.getModelRegistry().getObject(location);
if(location.getPath().contains("runestone") || location.getPath().contains("runestone_pedestal")){
IBakedModel original = event.getModelRegistry().getObject(location);
event.getModelRegistry().putObject(location, new BakedModelGlowingOverlay(original, "overlay"));
}else if(location.getPath().contains("spectral_block")){
IBakedModel original = event.getModelRegistry().getObject(location);
event.getModelRegistry().putObject(location, new BakedModelGlowingOverlay(original, "spectral_block"));
}
}
@@ -1,6 +1,7 @@
package electroblob.wizardry.client.particle;
import electroblob.wizardry.Wizardry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
@@ -15,6 +16,8 @@ import javax.annotation.Nullable;
/** Superclass for particles with a second target entity or target position. */
public abstract class ParticleTargeted extends ParticleWizardry {
private static final double THIRD_PERSON_AXIAL_OFFSET = 1.2;
protected double targetX;
protected double targetY;
protected double targetZ;
@@ -79,6 +82,16 @@ public abstract class ParticleTargeted extends ParticleWizardry {
float y = (float)(this.prevPosY + (this.posY - this.prevPosY) * (double)partialTicks);
float z = (float)(this.prevPosZ + (this.posZ - this.prevPosZ) * (double)partialTicks);
// Translates the particle a short distance in front of the entity
if(this.entity != null && this.shouldApplyOriginOffset()){ // TODO: Replace with a protected boolean method
if(this.entity != viewer || Minecraft.getMinecraft().gameSettings.thirdPersonView != 0){
Vec3d look = entity.getLook(partialTicks).scale(THIRD_PERSON_AXIAL_OFFSET);
x += look.x;
y += look.y;
z += look.z;
}
}
if(this.target != null){
this.targetX = this.target.prevPosX + (this.target.posX - this.target.prevPosX) * partialTicks;
@@ -133,6 +146,12 @@ public abstract class ParticleTargeted extends ParticleWizardry {
GlStateManager.popMatrix();
}
/** Returns whether the origin of this particle should be moved a short distance in front of the entity it is
* linked to, if any. */
protected boolean shouldApplyOriginOffset(){
return true;
}
/** Called from {@link ParticleTargeted#renderParticle(BufferBuilder, Entity, float, float, float, float, float, float)},
* once the appropriate calculations and transformations have been applied, to actually render the particle. Subclasses
* override this <i>instead</i> of overriding {@code renderParticle} directly, and inside render the particle <b>along
@@ -46,6 +46,11 @@ public class ParticleVine extends ParticleTargeted {
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP);
}
@Override
protected boolean shouldApplyOriginOffset(){
return false;
}
@Override
protected void draw(Tessellator tessellator, double length, float partialTicks){