file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MeleeAttackCircle.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/MeleeAttackCircle.java
package untamedwilds.entity.ai; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.pathfinder.Node; import net.minecraft.world.level.pathfinder.Path; import java.util.EnumSet; public class MeleeAttackCircle extends Goal { protected final PathfinderMob attacker; protected int attackTick; private final double speedTowardsTarget; private final boolean longMemory; private Path path; private int delayCounter; private double targetX; private double targetY; private double targetZ; private float extraReach; private long field_220720_k; private int failedPathFindingPenalty = 0; private boolean canPenalize = false; private byte invert = 1; public MeleeAttackCircle(PathfinderMob entityIn, double speedIn, boolean useLongMemory) { this(entityIn, speedIn, useLongMemory, 0); } public MeleeAttackCircle(PathfinderMob entityIn, double speedIn, boolean useLongMemory, float reach) { this.attacker = entityIn; this.speedTowardsTarget = speedIn; this.longMemory = useLongMemory; this.extraReach = reach; this.setFlags(EnumSet.of(Flag.MOVE, Flag.TARGET, Flag.LOOK)); } @Override public boolean canUse() { if (this.attacker.isBaby()) { return false; } long i = this.attacker.level.getGameTime(); if (i - this.field_220720_k < 20L) { return false; } else { this.field_220720_k = i; LivingEntity livingentity = this.attacker.getTarget(); if (livingentity == null) { return false; } else if (!livingentity.isAlive()) { return false; } else { if (canPenalize) { if (--this.delayCounter <= 0) { this.path = this.attacker.getNavigation().createPath(livingentity, 0); this.delayCounter = 4 + this.attacker.getRandom().nextInt(7); return this.path != null; } else { return true; } } this.path = this.attacker.getNavigation().createPath(livingentity, 0); return this.path != null; } } } @Override public boolean canContinueToUse() { LivingEntity livingentity = this.attacker.getTarget(); if (livingentity == null || (this.attacker.getAirSupply() < 40 && !this.attacker.canBreatheUnderwater()) || !livingentity.isAlive()) { return false; } else if (!this.longMemory) { return !this.attacker.getNavigation().isDone(); } else { return !(livingentity instanceof Player) || !livingentity.isSpectator() && !((Player)livingentity).isCreative(); } } public void start() { this.attacker.getNavigation().moveTo(this.path, this.speedTowardsTarget); this.attacker.setAggressive(true); this.delayCounter = 0; } public void stop() { LivingEntity livingentity = this.attacker.getTarget(); if (livingentity == null || !TargetingConditions.forCombat().test(this.attacker, livingentity)) { this.attacker.setTarget(null); } this.attacker.setAggressive(false); this.attacker.getNavigation().stop(); } public void tick() { LivingEntity livingentity = this.attacker.getTarget(); double d0 = this.attacker.distanceToSqr(livingentity.getX(), livingentity.getBoundingBox().minY, livingentity.getZ()); --this.delayCounter; if ((this.longMemory || this.attacker.getSensing().hasLineOfSight(livingentity)) && this.delayCounter <= 0 && (this.targetX == 0.0D && this.targetY == 0.0D && this.targetZ == 0.0D || livingentity.distanceToSqr(this.targetX, this.targetY, this.targetZ) >= 1.0D || this.attacker.getRandom().nextFloat() < 0.05F)) { this.targetX = livingentity.getX(); this.targetY = livingentity.getBoundingBox().minY; this.targetZ = livingentity.getZ(); // Circling if (this.attacker.tickCount % 400 == 0) { this.invert *= -1; } if (this.attacker.tickCount % 400 > 80) { if (this.attacker.getTarget() != null && this.attacker.tickCount % 10 == 0) { double x = this.attacker.getTarget().getX() + Math.cos(this.attacker.tickCount / 60F) * 10 * this.invert; double z = this.attacker.getTarget().getZ() + Math.sin(this.attacker.tickCount / 60F) * 10 * this.invert; this.attacker.getNavigation().moveTo(x, this.attacker.getTarget().getY(), z, 2.3F); } } // Attacking else { this.attacker.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); this.delayCounter = 4 + this.attacker.getRandom().nextInt(7); if (this.canPenalize) { this.delayCounter += failedPathFindingPenalty; if (this.attacker.getNavigation().getPath() != null) { Node finalPathPoint = this.attacker.getNavigation().getPath().getEndNode(); if (finalPathPoint != null && livingentity.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) failedPathFindingPenalty = 0; else failedPathFindingPenalty += 10; } else { failedPathFindingPenalty += 10; } } if (d0 > 1024.0D) { this.delayCounter += 10; } else if (d0 > 256.0D) { this.delayCounter += 5; } if (!this.attacker.getNavigation().moveTo(livingentity, this.speedTowardsTarget * 1.5F)) { this.delayCounter += 15; } } } this.attackTick = Math.max(this.attackTick - 1, 0); this.checkAndPerformAttack(livingentity, this.attacker.distanceToSqr(this.targetX, this.targetY, this.targetZ)); } protected void checkAndPerformAttack(LivingEntity enemy, double distToEnemySqr) { double d0 = this.getAttackReachSqr(enemy); if (this.attacker.hasLineOfSight(enemy) && distToEnemySqr <= d0 && this.attackTick <= 0) { this.attackTick = 20; this.attacker.doHurtTarget(enemy); this.attacker.getLookControl().setLookAt(enemy, 30.0F, 30.0F); } } protected double getAttackReachSqr(LivingEntity attackTarget) { return (this.attacker.getBbWidth() * 2.0F * this.attacker.getBbWidth() * 2.0F + attackTarget.getBbWidth() + this.extraReach); } }
7,109
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartAvoidGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/SmartAvoidGoal.java
package untamedwilds.entity.ai; import net.minecraft.world.entity.EntitySelector; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.AvoidEntityGoal; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.ai.util.DefaultRandomPos; import net.minecraft.world.phys.Vec3; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class SmartAvoidGoal <T extends LivingEntity> extends AvoidEntityGoal<T> { protected ComplexMob taskOwner; protected final float avoidDistance; private final TargetingConditions builtTargetSelector; public SmartAvoidGoal(ComplexMob entityIn, Class<T> classToAvoidIn, float avoidDistanceIn, double farSpeedIn, double nearSpeedIn, final Predicate<LivingEntity> targetSelector) { super(entityIn, classToAvoidIn, avoidDistanceIn, farSpeedIn, nearSpeedIn, EntitySelector.NO_CREATIVE_OR_SPECTATOR::test); this.taskOwner = entityIn; this.avoidDistance = avoidDistanceIn; this.builtTargetSelector = TargetingConditions.forCombat().range(avoidDistanceIn).selector(targetSelector); this.setFlags(EnumSet.of(Goal.Flag.MOVE)); } @Override public boolean canUse() { if (this.taskOwner.tickCount % 40 != 0) { return false; } if (this.taskOwner.getTarget() != null || this.taskOwner.isSleeping() || this.taskOwner.getCommandInt() != 0 || this.taskOwner.isTame()) { return false; } List<T> list = this.taskOwner.level.getNearbyEntities(avoidClass, this.builtTargetSelector, this.taskOwner, this.taskOwner.getBoundingBox().inflate(avoidDistance, 4f, avoidDistance)); if (list.isEmpty()) { return false; } else { this.toAvoid = list.get(0); Vec3 vec3d = DefaultRandomPos.getPosAway(this.taskOwner, 16, 7, new Vec3(this.toAvoid.getX(), this.toAvoid.getY(), this.toAvoid.getZ())); if (vec3d == null) { return false; } else if (this.toAvoid.distanceToSqr(vec3d.x, vec3d.y, vec3d.z) < this.toAvoid.distanceToSqr(this.mob)) { return false; } else { this.path = this.pathNav.createPath(vec3d.x, vec3d.y, vec3d.z, 0); return this.path != null; } } } }
2,510
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
AmphibiousRandomSwimGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/AmphibiousRandomSwimGoal.java
package untamedwilds.entity.ai; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.ai.behavior.BehaviorUtils; import net.minecraft.world.entity.ai.goal.RandomSwimmingGoal; import net.minecraft.world.phys.Vec3; import untamedwilds.entity.ComplexMobAmphibious; import javax.annotation.Nullable; public class AmphibiousRandomSwimGoal extends RandomSwimmingGoal { public static final int[][] XY_DISTANCE_TIERS = new int[][]{{1, 1}, {3, 3}, {5, 5}, {6, 5}, {7, 7}, {10, 7}}; private final ComplexMobAmphibious fish; public AmphibiousRandomSwimGoal(ComplexMobAmphibious entityIn, double speedIn, int chance) { super(entityIn, speedIn, chance); this.fish = entityIn; } public boolean canUse() { if (!this.fish.isInWater() && this.fish.wantsToBeOnLand()) { return false; } return super.canUse(); } @Nullable protected Vec3 getPosition() { Vec3 vec3 = null; Vec3 vec31 = null; for(int[] aint : XY_DISTANCE_TIERS) { if (vec3 == null) { vec31 = BehaviorUtils.getRandomSwimmablePos(this.fish, aint[0], aint[1]); } else { vec31 = this.fish.position().add(this.fish.position().vectorTo(vec3).normalize().multiply(aint[0], aint[1], aint[0])); } if (vec31 == null || this.fish.level.getFluidState(new BlockPos(vec31)).isEmpty()) { return vec3; } vec3 = vec31; } return vec31; } }
1,541
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartSwimGoal_Land.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/SmartSwimGoal_Land.java
package untamedwilds.entity.ai; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.tags.FluidTags; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.mammal.EntityBear; import untamedwilds.util.EntityUtils; import java.util.EnumSet; import java.util.List; public class SmartSwimGoal_Land extends Goal { private final ComplexMob entity; private final float speed; public SmartSwimGoal_Land(ComplexMob entityIn) { this(entityIn, 0.7f); } public SmartSwimGoal_Land(ComplexMob entityIn, float speedIn) { this.entity = entityIn; this.speed = speedIn; this.setFlags(EnumSet.of(Flag.JUMP)); entityIn.getNavigation().setCanFloat(true); } @Override public boolean canUse() { if (this.entity.isInWater() && this.entity.getTarget() == null && this.entity.getNavigation().canFloat()) { double eyeHeight = (double) this.entity.getEyeHeight() - (this.entity.isBaby() ? -0.8 : 0.18F); // Tiny offset because otherwise the Mob drowns return this.entity.getFluidHeight(FluidTags.WATER) > eyeHeight || this.entity.isInLava(); } return false; } @Override public void start() { if (!this.entity.canMove()) { this.entity.setSleeping(false); this.entity.setSitting(false); if (this.entity.getCommandInt() == 2) { this.entity.setCommandInt(0); } } } @Override public boolean canContinueToUse() { return !this.entity.isOnGround() && this.entity.isInWater() && this.entity.getTarget() == null; } @Override public void tick() { if (this.entity.getNavigation().isDone()) { this.entity.getMoveControl().strafe(this.speed, 0); } boolean colliding = this.entity.level.collidesWithSuffocatingBlock(this.entity, this.entity.getBoundingBox().expandTowards(this.entity.getLookAngle())); if (this.entity.isEyeInFluid(FluidTags.WATER) || colliding) { this.entity.getJumpControl().jump(); } if (this.entity.tickCount % 6 == 0) { EntityUtils.spawnParticlesOnEntity(this.entity.level, this.entity, ParticleTypes.SPLASH, 4, 2); } } /*public SmartSwimGoal_Land(ComplexMob entityIn) { this(entityIn, 0.7f); } public SmartSwimGoal_Land(ComplexMob entityIn, float speedIn) { this.entity = entityIn; this.speed = speedIn; this.setFlags(EnumSet.of(Flag.MOVE)); entityIn.getNavigation().setCanFloat(true); } public boolean canUse() { return this.entity.isInWater() && this.entity.getFluidHeight(FluidTags.WATER) > this.entity.getFluidJumpThreshold() || this.entity.isInLava(); } public boolean requiresUpdateEveryTick() { return true; } public void tick() { if (this.entity.getRandom().nextFloat() < 0.8F) { this.entity.getJumpControl().jump(); } }*/ } /*public SmartSwimGoal_Land(ComplexMob entityIn) { this(entityIn, 0.7f); } public SmartSwimGoal_Land(ComplexMob entityIn, float speedIn) { this.entity = entityIn; this.speed = speedIn; this.setFlags(EnumSet.of(Flag.MOVE)); entityIn.getNavigation().setCanFloat(true); } @Override public boolean canUse() { if (this.entity.isInWater() && this.entity.getTarget() == null && this.entity.getNavigation().canFloat()) { double eyeHeight = (double) this.entity.getEyeHeight() - (this.entity.isBaby() ? -0.8 : 0.18F); // Tiny offset because otherwise the Mob drowns return true; //return this.entity.getFluidHeight(FluidTags.WATER) > eyeHeight || this.entity.isInLava(); } return false; } @Override public void start() { if (!this.entity.canMove()) { this.entity.setSleeping(false); this.entity.setSitting(false); if (this.entity.getCommandInt() == 2) { this.entity.setCommandInt(0); } } } @Override public boolean canContinueToUse() { return !this.entity.isOnGround() && this.entity.isInWater() && this.entity.getTarget() == null; } @Override public void tick() { this.entity.getMoveControl().strafe(this.speed, 0); if (this.entity.getNavigation().isDone()) { this.entity.getMoveControl().strafe(this.speed, 0); //this.entity.getMoveControl().strafe(this.speed, 0); } if (this.entity.isEyeInFluid(FluidTags.WATER) || this.entity.horizontalCollision) { this.entity.getJumpControl().jump(); } if (this.entity.tickCount % 6 == 0) { EntityUtils.spawnParticlesOnEntity(this.entity.level, this.entity, ParticleTypes.SPLASH, 4, 2); } } }*/
5,154
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SpitterAttackGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/SpitterAttackGoal.java
package untamedwilds.entity.ai.unique; import com.github.alexthe666.citadel.animation.IAnimatedEntity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.pathfinder.Node; import net.minecraft.world.level.pathfinder.Path; import net.minecraft.world.phys.Vec3; import untamedwilds.entity.relict.EntitySpitter; import java.util.EnumSet; import java.util.List; public class SpitterAttackGoal extends Goal { protected final EntitySpitter attacker; protected int attackTick; private final double speedTowardsTarget; private final boolean longMemory; private Path path; private int delayCounter; private double targetX; private double targetY; private double targetZ; private final float extraReach; private long field_220720_k; private int failedPathFindingPenalty = 0; private final boolean canPenalize = false; public SpitterAttackGoal(EntitySpitter entityIn, double speedIn, boolean useLongMemory, float reach) { this.attacker = entityIn; this.speedTowardsTarget = speedIn; this.longMemory = useLongMemory; this.extraReach = reach; this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); } @Override public boolean canUse() { long i = this.attacker.level.getGameTime(); if (i - this.field_220720_k < 20L) { return false; } else { this.field_220720_k = i; LivingEntity livingentity = this.attacker.getTarget(); if (livingentity == null) { return false; } else if (!livingentity.isAlive()) { return false; } else { if (canPenalize) { if (--this.delayCounter <= 0) { this.path = this.attacker.getNavigation().createPath(livingentity, 0); this.delayCounter = 4 + this.attacker.getRandom().nextInt(7); return this.path != null; } else { return true; } } this.path = this.attacker.getNavigation().createPath(livingentity, 0); return this.path != null; } } } @Override public boolean canContinueToUse() { LivingEntity livingentity = this.attacker.getTarget(); if (livingentity == null || (this.attacker.getAirSupply() < 40 && !this.attacker.canBreatheUnderwater()) || !livingentity.isAlive()) { return false; } else if (!this.longMemory) { return !this.attacker.getNavigation().isDone(); } else if (!this.attacker.isWithinRestriction(livingentity.blockPosition())) { return false; } else { return !(livingentity instanceof Player) || !livingentity.isSpectator() && !((Player)livingentity).isCreative(); } } public void start() { if (!this.attacker.isBaby()) this.attacker.getNavigation().moveTo(this.path, this.speedTowardsTarget); this.attacker.setAggressive(true); this.delayCounter = 0; List<? extends EntitySpitter> list = this.attacker.level.getEntitiesOfClass(EntitySpitter.class, this.attacker.getBoundingBox().inflate(12.0D, 8.0D, 12.0D)); for (EntitySpitter entityanimal1 : list) { if (entityanimal1.getVariant() == this.attacker.getVariant()) { entityanimal1.setTarget(this.attacker.getTarget()); } } } public void stop() { /*LivingEntity livingentity = this.attacker.getTarget(); if (!TargetingConditions.forCombat().test(this.attacker, livingentity)) { this.attacker.setTarget(null); }*/ this.attacker.setTarget(null); // <- Edited this.attacker.setAggressive(false); this.attacker.getNavigation().stop(); } public void tick() { LivingEntity livingentity = this.attacker.getTarget(); this.attacker.getLookControl().setLookAt(Vec3.atCenterOf(livingentity.blockPosition())); //this.attacker.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); double d0 = this.attacker.distanceToSqr(livingentity.getX(), livingentity.getBoundingBox().minY, livingentity.getZ()); --this.delayCounter; // This piece of code fixes mobs in water being unable to chase upwards if (this.attacker.isInWater() && this.attacker.tickCount % 12 == 0) { if ((livingentity.getBoundingBox().minY - 2) > this.attacker.getY()) { this.attacker.getJumpControl().jump(); } } if (this.attacker.getAnimation() == EntitySpitter.NO_ANIMATION && this.attacker.getSensing().hasLineOfSight(livingentity) && this.attacker.getRandom().nextInt(this.attacker.isBaby() ? 80 : 200) == 0 && d0 > 12) { // TODO: random chance = 200 this.attacker.getLookControl().setLookAt(livingentity); this.attacker.setAnimation(EntitySpitter.ATTACK_SPIT); } else if (!this.attacker.isBaby() && (this.longMemory || this.attacker.getSensing().hasLineOfSight(livingentity)) && this.delayCounter <= 0 && (this.targetX == 0.0D && this.targetY == 0.0D && this.targetZ == 0.0D || livingentity.distanceToSqr(this.targetX, this.targetY, this.targetZ) >= 1.0D || this.attacker.getRandom().nextFloat() < 0.05F)) { this.targetX = livingentity.getX(); this.targetY = livingentity.getBoundingBox().minY; this.targetZ = livingentity.getZ(); this.delayCounter = 4 + this.attacker.getRandom().nextInt(7); if (this.canPenalize) { this.delayCounter += failedPathFindingPenalty; if (this.attacker.getNavigation().getPath() != null) { Node finalPathPoint = this.attacker.getNavigation().getPath().getEndNode(); if (finalPathPoint != null && livingentity.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) failedPathFindingPenalty = 0; else failedPathFindingPenalty += 10; } else { failedPathFindingPenalty += 10; } } if (d0 > 1024.0D) { this.delayCounter += 10; } else if (d0 > 256.0D) { this.delayCounter += 5; } if (!this.attacker.getNavigation().moveTo(livingentity, this.speedTowardsTarget)) { this.delayCounter += 15; } } this.attackTick = Math.max(this.attackTick - 1, 0); this.checkAndPerformAttack(livingentity, d0); } protected void checkAndPerformAttack(LivingEntity enemy, double distToEnemySqr) { double d0 = this.getAttackReachSqr(enemy); if (this.attacker.hasLineOfSight(enemy) && distToEnemySqr <= d0 && (this.attackTick <= 0 || (this.attackTick <= 10 && this.attacker.getAnimation() == IAnimatedEntity.NO_ANIMATION))) { this.attackTick = 20; this.attacker.doHurtTarget(enemy); } } protected double getAttackReachSqr(LivingEntity attackTarget) { return (this.attacker.getBbWidth() * 2.0F * this.attacker.getBbWidth() * 2.0F + attackTarget.getBbWidth() + this.extraReach); } }
7,469
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
HippoTerritoryTargetGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/HippoTerritoryTargetGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ai.target.HuntMobTarget; import java.util.function.Predicate; public class HippoTerritoryTargetGoal<T extends LivingEntity> extends HuntMobTarget<T> { public HippoTerritoryTargetGoal(ComplexMob creature, Class<T> classTarget, boolean checkSight, boolean onlyNearby, final Predicate<? super T > targetSelector) { super(creature, classTarget, checkSight,200, false, ((Predicate<LivingEntity>)null)); this.targetEntitySelector = (Predicate<T>) entity -> { if (targetSelector != null && !targetSelector.test(entity)) { return false; } else { return TargetingConditions.forCombat().test(creature, entity) && this.canAttack(entity, TargetingConditions.DEFAULT); } }; } public boolean canUse() { if (mob.isBaby() || !mob.isInWater()) { return false; } return super.canUse(); } }
1,155
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
PandaEatBamboo.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/PandaEatBamboo.java
package untamedwilds.entity.ai.unique; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.Item; import net.minecraft.world.phys.AABB; import untamedwilds.entity.ComplexMobTerrestrial; import java.util.Comparator; import java.util.EnumSet; import java.util.List; public class PandaEatBamboo extends Goal { private final ComplexMobTerrestrial taskOwner; private final Sorter sorter; private final int executionChance; private final int distance; private ItemEntity targetItem; private Item targetItemStack; public PandaEatBamboo(ComplexMobTerrestrial creature, int chance, int distance) { this.taskOwner = creature; this.executionChance = chance; this.sorter = new Sorter(creature); this.distance = distance; this.setFlags(EnumSet.of(Flag.MOVE, Flag.TARGET)); } public boolean canUse() { if (this.taskOwner.getHunger() > 80 || this.taskOwner.isBaby() || this.taskOwner.isSleeping()) { return false; } if (this.taskOwner.getRandom().nextInt(this.executionChance) != 0) { return false; } List<ItemEntity> list = this.taskOwner.level.getEntitiesOfClass(ItemEntity.class, this.getTargetableArea(distance)); list.removeIf((ItemEntity item) -> item.getItem().getItem().equals("bamboo")); // Stupid way to do this if (list.isEmpty()) { return false; } else { list.sort(this.sorter); this.targetItem = list.get(0); this.targetItemStack = this.targetItem.getItem().getItem(); return true; } } private AABB getTargetableArea(double targetDistance) { return this.taskOwner.getBoundingBox().inflate(targetDistance, 4.0D, targetDistance); } public void start() { this.taskOwner.getNavigation().moveTo(this.targetItem.getX(), this.targetItem.getY(), this.targetItem.getZ(), 1D); } @Override public boolean canContinueToUse() { if (this.targetItem == null || !this.targetItem.isAlive()) { return false; } else if (this.taskOwner.isSitting()) { return false; } return !this.taskOwner.isPathFinding(); } @Override public void tick() { double distance = Math.sqrt(Math.pow(this.taskOwner.getX() - this.targetItem.getX(), 2.0D) + Math.pow(this.taskOwner.getZ() - this.targetItem.getZ(), 2.0D)); if (distance < 1.5D) { this.taskOwner.addHunger(10); this.targetItem.getItem().shrink(1); if (this.targetItem.getItem().getCount() == 0) { this.targetItem.discard(); } this.taskOwner.setAnimation(taskOwner.getAnimationEat()); } if(this.taskOwner.getNavigation().isDone()){ stop(); } this.taskOwner.getNavigation().moveTo(this.targetItem.getX(), this.targetItem.getY(), this.targetItem.getZ(), 1D); } public static class Sorter implements Comparator<Entity> { private final Entity entity; private Sorter(Entity entityIn) { this.entity = entityIn; } public int compare(Entity entity_1, Entity entity_2) { double dist_1 = this.entity.distanceToSqr(entity_1); double dist_2 = this.entity.distanceToSqr(entity_2); if (dist_1 < dist_2) { return -1; } else { return dist_1 > dist_2 ? 1 : 0; } } } }
3,666
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SharkSwimmingGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/SharkSwimmingGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.ai.behavior.BehaviorUtils; import net.minecraft.world.entity.ai.goal.RandomSwimmingGoal; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import untamedwilds.entity.fish.EntityShark; import javax.annotation.Nullable; public class SharkSwimmingGoal extends RandomSwimmingGoal { private EntityShark taskOwner; public SharkSwimmingGoal(EntityShark entity) { super(entity, 1.0D, 20); this.taskOwner = entity; } @Nullable protected Vec3 getPosition() { Vec3 vector3d = BehaviorUtils.getRandomSwimmablePos(this.taskOwner, 10, 7); for(int i = 0; vector3d != null && !this.taskOwner.level.getBlockState(new BlockPos(vector3d)).isPathfindable(this.taskOwner.level, new BlockPos(vector3d), PathComputationType.WATER) && i++ < 10; vector3d = BehaviorUtils.getRandomSwimmablePos(this.taskOwner, 10, 7)) { } if (this.taskOwner.isBottomDweller() && vector3d != null && this.taskOwner.level.canSeeSkyFromBelowWater(this.taskOwner.blockPosition())) { int offset = 5 + this.taskOwner.getRandom().nextInt(7) - 4; return new Vec3(vector3d.x(), this.taskOwner.level.getHeight(Heightmap.Types.OCEAN_FLOOR, (int)vector3d.x(), (int)vector3d.z()) + offset, vector3d.z()); } return vector3d; } }
1,506
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
WhaleBreachGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/WhaleBreachGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.tags.FluidTags; import net.minecraft.util.Mth; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.ai.goal.JumpGoal; import net.minecraft.world.entity.animal.Dolphin; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.phys.Vec3; import untamedwilds.entity.ComplexMobAmphibious; import untamedwilds.entity.ComplexMobAquatic; public class WhaleBreachGoal extends JumpGoal { private static final int[] STEPS_TO_CHECK = new int[]{0, 8, 9, 12, 14}; private final ComplexMobAquatic dolphin; private final int interval; private boolean breached; public WhaleBreachGoal(ComplexMobAquatic p_25168_, int p_25169_) { this.dolphin = p_25168_; this.interval = reducedTickDelay(p_25169_); } public boolean canUse() { if (this.dolphin.getRandom().nextInt(this.interval) != 0) { return false; } else { Direction direction = this.dolphin.getMotionDirection(); int i = direction.getStepX(); int j = direction.getStepZ(); BlockPos blockpos = this.dolphin.blockPosition(); for(int k : STEPS_TO_CHECK) { if (!this.waterIsClear(blockpos, i, j, k) || !this.surfaceIsClear(blockpos, i, j, k)) { return false; } } //this.dolphin.addEffect(new MobEffectInstance(MobEffects.SLOW_FALLING, 80, 0)); return true; } } private boolean waterIsClear(BlockPos p_25173_, int p_25174_, int p_25175_, int p_25176_) { BlockPos blockpos = p_25173_.offset(p_25174_ * p_25176_, 0, p_25175_ * p_25176_); return this.dolphin.level.getFluidState(blockpos).is(FluidTags.WATER) && !this.dolphin.level.getBlockState(blockpos).getMaterial().blocksMotion(); } private boolean surfaceIsClear(BlockPos p_25179_, int p_25180_, int p_25181_, int p_25182_) { return this.dolphin.level.getBlockState(p_25179_.offset(p_25180_ * p_25182_, 1, p_25181_ * p_25182_)).isAir() && this.dolphin.level.getBlockState(p_25179_.offset(p_25180_ * p_25182_, 2, p_25181_ * p_25182_)).isAir(); } public boolean canContinueToUse() { double d0 = this.dolphin.getDeltaMovement().y; return (!(d0 * d0 < (double)0.03F) || this.dolphin.getXRot() == 0.0F || !(Math.abs(this.dolphin.getXRot()) < 10.0F) || !this.dolphin.isInWater()) && !this.dolphin.isOnGround(); } public boolean isInterruptable() { return false; } public void start() { Direction direction = this.dolphin.getMotionDirection(); this.dolphin.setDeltaMovement(this.dolphin.getDeltaMovement().add((double)direction.getStepX() * 0.6D, 0.7D, (double)direction.getStepZ() * 0.6D)); this.dolphin.getNavigation().stop(); } public void stop() { this.dolphin.setXRot(0.0F); } public void tick() { boolean flag = this.breached; if (!flag) { FluidState fluidstate = this.dolphin.level.getFluidState(this.dolphin.blockPosition()); this.breached = fluidstate.is(FluidTags.WATER); } if (this.breached && !flag) { this.dolphin.playSound(SoundEvents.DOLPHIN_JUMP, 1.0F, 1.0F); } Vec3 vec3 = this.dolphin.getDeltaMovement(); if (vec3.y * vec3.y < (double)0.03F && this.dolphin.getXRot() != 0.0F) { this.dolphin.setXRot(Mth.rotlerp(this.dolphin.getXRot(), 0.0F, 0.2F)); } else if (vec3.length() > (double)1.0E-5F) { double d0 = vec3.horizontalDistance(); double d1 = Math.atan2(-vec3.y, d0) * (double)(180F / (float)Math.PI); this.dolphin.setXRot((float)d1); } } }
3,956
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
PandaBreakBamboo.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/PandaBreakBamboo.java
package untamedwilds.entity.ai.unique; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.pathfinder.Path; import untamedwilds.entity.mammal.EntityBear; import java.util.EnumSet; public class PandaBreakBamboo extends Goal { private BlockPos targetPos; private final EntityBear taskOwner; private final int executionChance; private Path path; private int searchCooldown; private boolean continueTask; public PandaBreakBamboo(EntityBear entityIn, int chance) { this.taskOwner = entityIn; this.executionChance = chance; this.searchCooldown = 100; this.continueTask = true; this.setFlags(EnumSet.of(Flag.MOVE)); } public boolean canUse() { if (!this.taskOwner.isOnGround() || this.taskOwner.getHunger() > 40) { return false; } if (this.taskOwner.getTarget() != null) { return false; } if (this.taskOwner.getRandom().nextInt(this.executionChance) != 0) { return false; } BlockPos pos = this.taskOwner.blockPosition(); this.targetPos = findNearbyBamboo(pos); if (this.targetPos != null) { this.path = this.taskOwner.getNavigation().createPath(this.targetPos, 0); return this.path != null; } return false; } public void start() { this.taskOwner.getNavigation().moveTo(this.path, 1); super.start(); } public void stop() { } public void tick() { // For some fucking reason, Panda Bears stop long before reaching their target block this.taskOwner.getLookControl().setLookAt(this.targetPos.getX(), this.targetPos.getY() + 1.5F, this.targetPos.getZ(), 10f, (float)this.taskOwner.getMaxHeadXRot()); if (!this.taskOwner.isSitting()) { this.taskOwner.getMoveControl().strafe(1, 0); } if (this.targetPos != null && this.taskOwner.distanceToSqr(targetPos.getX(), targetPos.getY(), targetPos.getZ()) < 5) { this.taskOwner.getLookControl().setLookAt(this.targetPos.getX(), this.targetPos.getY() + 1.5F, this.targetPos.getZ(), 10f, (float)this.taskOwner.getMaxHeadXRot()); this.taskOwner.getNavigation().stop(); this.taskOwner.setSitting(true); this.searchCooldown--; if (this.searchCooldown == 0) { this.searchCooldown = 100; this.taskOwner.level.destroyBlock(this.targetPos.above(), false); this.taskOwner.setAnimation(EntityBear.ATTACK_SWIPE); // TODO: Make the Panda hold the Bamboo and chew it this.taskOwner.addHunger(8); this.continueTask = false; } } super.tick(); } public boolean canContinueToUse() { if (!this.continueTask) { this.taskOwner.setSitting(false); return false; } return true; } public BlockPos findNearbyBamboo(BlockPos blockpos) { BlockPos.MutableBlockPos blockpos$mutable = new BlockPos.MutableBlockPos(); for(int i = 0; i < 3; ++i) { for(int j = 0; j < 8; ++j) { for(int k = 0; k <= j; k = k > 0 ? -k : 1 - k) { for(int l = k < j && k > -j ? j : 0; l <= j; l = l > 0 ? -l : 1 - l) { blockpos$mutable.set(blockpos).move(k, i, l); if (this.taskOwner.level.getBlockState(blockpos$mutable).getBlock() == Blocks.BAMBOO && this.taskOwner.level.getBlockState(blockpos$mutable.above()).getBlock() == Blocks.BAMBOO) { return blockpos$mutable; } } } } } return null; } }
3,885
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
TortoiseHideInShellGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/TortoiseHideInShellGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import untamedwilds.entity.ComplexMob; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class TortoiseHideInShellGoal<T extends LivingEntity> extends Goal { protected final Class<T> classToAvoid; protected T avoidTarget; protected ComplexMob taskOwner; protected final float avoidDistance; private final TargetingConditions builtTargetSelector; public TortoiseHideInShellGoal(ComplexMob entityIn, Class<T> classToAvoidIn, float avoidDistanceIn, final Predicate<LivingEntity> targetSelector) { this.taskOwner = entityIn; this.classToAvoid = classToAvoidIn; this.avoidDistance = avoidDistanceIn; this.builtTargetSelector = TargetingConditions.forCombat().range(avoidDistanceIn).selector(targetSelector); this.setFlags(EnumSet.of(Flag.MOVE)); } @Override public boolean canUse() { if (this.taskOwner.tickCount % 40 != 0) { return false; } if (this.taskOwner.getTarget() != null || this.taskOwner.getCommandInt() != 0 || this.taskOwner.isTame()) { return false; } List<T> list = this.taskOwner.level.getNearbyEntities(classToAvoid, this.builtTargetSelector, this.taskOwner, this.taskOwner.getBoundingBox().inflate(avoidDistance, 4f, avoidDistance)); if (list.isEmpty()) { this.taskOwner.setSitting(false); return false; } this.avoidTarget = list.get(0); return true; } public void start() { super.start(); this.taskOwner.getNavigation().stop(); this.taskOwner.setSitting(true); } public void stop() { super.stop(); } public void tick() { if (this.taskOwner.getRandom().nextInt(40) == 0) { List<T> list = this.taskOwner.level.getNearbyEntities(classToAvoid, this.builtTargetSelector, this.taskOwner, this.taskOwner.getBoundingBox().inflate(avoidDistance, 4f, avoidDistance)); if (list.isEmpty()) { this.taskOwner.setSitting(false); } } if (this.taskOwner.distanceTo(this.avoidTarget) > 10) { this.taskOwner.setSitting(false); } super.tick(); } public boolean canContinueToUse() { return !this.taskOwner.isSitting(); } }
2,548
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
BaleenWhaleFeedGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/BaleenWhaleFeedGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.ai.behavior.BehaviorUtils; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import untamedwilds.UntamedWilds; import untamedwilds.entity.mammal.EntityBaleenWhale; import javax.annotation.Nullable; import java.util.EnumSet; public class BaleenWhaleFeedGoal extends Goal { private final EntityBaleenWhale taskOwner; private final int chance; private BlockPos targetPos; private int eatingCounter; public BaleenWhaleFeedGoal(EntityBaleenWhale entityIn, int chance) { this.taskOwner = entityIn; this.chance = chance; this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK)); } public boolean canUse() { if (this.taskOwner.getRandom().nextInt(this.chance) == 0) { this.targetPos = getPosition(); return this.targetPos != null; } return false; } @Nullable protected BlockPos getPosition() { Vec3 vector3d = BehaviorUtils.getRandomSwimmablePos(this.taskOwner, 20, 7); for(int i = 0; vector3d != null && !this.taskOwner.level.getBlockState(new BlockPos(vector3d)).isPathfindable(this.taskOwner.level, new BlockPos(vector3d), PathComputationType.WATER) && i++ < 10; vector3d = BehaviorUtils.getRandomSwimmablePos(this.taskOwner, 20, 7)) { } if (vector3d != null && this.taskOwner.level.canSeeSky(this.taskOwner.blockPosition())) { int offset = 5 + this.taskOwner.getRandom().nextInt(7) - 4; return new BlockPos(vector3d.x(), this.taskOwner.level.getHeight(Heightmap.Types.OCEAN_FLOOR, (int)vector3d.x(), (int)vector3d.z()) + offset, vector3d.z()); } if (vector3d != null) { return new BlockPos(vector3d); } return null; } public boolean canContinueToUse() { //UntamedWilds.LOGGER.info((!this.taskOwner.getNavigation().isDone()) + " " + (this.eatingCounter != 0)); return !this.taskOwner.getNavigation().isDone() && this.eatingCounter != 0; } public void start() { this.eatingCounter = 200; this.taskOwner.setFeeding(true); this.taskOwner.getNavigation().moveTo(this.targetPos.getX() + 0.5, this.targetPos.above().getY(), this.targetPos.getZ() + 0.5, 1.5); } public void stop() { //UntamedWilds.LOGGER.info("STOPPING"); if (this.taskOwner.isFeeding()) this.taskOwner.setFeeding(false); super.stop(); } public void tick() { //UntamedWilds.LOGGER.info(this.sinkingCounter); if (this.eatingCounter > 0) this.eatingCounter--; //this.eatingCounter = this.taskOwner.getRandom().nextInt(200) + 200; } public boolean isInterruptable() { return false; } }
2,981
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
BearRaidChestsGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/BearRaidChestsGoal.java
package untamedwilds.entity.ai.unique; import com.mojang.datafixers.util.Pair; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.ChestBlockEntity; import net.minecraft.world.level.block.state.BlockState; import untamedwilds.entity.mammal.EntityBear; import java.util.EnumSet; public class BearRaidChestsGoal extends Goal { private Container targetInventory; private BlockPos targetPos; private final EntityBear taskOwner; private final int executionChance; private int searchCooldown; private boolean continueTask; public BearRaidChestsGoal(EntityBear entityIn, int chance) { this.taskOwner = entityIn; this.executionChance = chance; this.searchCooldown = 100; this.continueTask = true; this.setFlags(EnumSet.of(Goal.Flag.MOVE)); } public boolean canUse() { if (this.taskOwner.isTame() || !this.taskOwner.isOnGround() || this.taskOwner.getHunger() > 60 || this.taskOwner.getRandom().nextInt(this.executionChance) != 0 || this.taskOwner.getTarget() != null) { return false; } BlockPos pos = this.taskOwner.blockPosition(); this.targetPos = getNearbyInventories(pos); return this.targetPos != null; } public void start() { this.taskOwner.getNavigation().moveTo((double)this.targetPos.getX() + 0.5D, this.targetPos.getY() + 1, (double)this.targetPos.getZ() + 0.5D, 1f); super.start(); } public void stop() { } public void tick() { //double distance = this.taskOwner.getDistance(this.targetInventory.getX(), this.targetBlock.getY(), this.targetBlock.getZ()); if (this.targetPos != null && this.taskOwner.distanceToSqr(targetPos.getX(), targetPos.getY(), targetPos.getZ()) < 4) { this.taskOwner.getLookControl().setLookAt(this.targetPos.getX(), this.targetPos.getY() + 1.5F, this.targetPos.getZ(), 10f, (float)this.taskOwner.getMaxHeadXRot()); this.taskOwner.getNavigation().stop(); this.taskOwner.setSitting(true); this.searchCooldown--; if (this.taskOwner.level.getBlockEntity(targetPos) instanceof ChestBlockEntity) { ChestBlockEntity chest = (ChestBlockEntity) this.taskOwner.level.getBlockEntity(targetPos); this.taskOwner.level.blockEvent(this.targetPos, chest.getBlockState().getBlock(), 1, 1); } if (this.searchCooldown == 0) { this.searchCooldown = 100; this.continueTask = stealItem(); } } super.tick(); } public boolean canContinueToUse() { if (this.taskOwner.getHunger() >= 60 || this.targetInventory.isEmpty()) { this.taskOwner.setSitting(false); if (this.taskOwner.level.getBlockEntity(targetPos) instanceof ChestBlockEntity) { ChestBlockEntity chest = (ChestBlockEntity) this.taskOwner.level.getBlockEntity(targetPos); this.taskOwner.level.blockEvent(this.targetPos, chest.getBlockState().getBlock(), 1, 0); } return false; } return this.continueTask; } private boolean stealItem() { if (this.targetInventory != null) { Direction enumfacing = Direction.DOWN; if (isInventoryEmpty(this.targetInventory, enumfacing)) { return false; } if (this.targetInventory instanceof WorldlyContainer) { WorldlyContainer isidedinventory = (WorldlyContainer) this.targetInventory; int[] aint = isidedinventory.getSlotsForFace(enumfacing); for (int i : aint) { ItemStack itemstack = this.targetInventory.getItem(i); if (!itemstack.isEmpty() && canExtractItemFromSlot(this.targetInventory, itemstack, i, enumfacing)) { ItemStack itemstack1 = itemstack.copy(); this.targetInventory.setItem(i, ItemStack.EMPTY); if (itemstack1.getItem().isEdible()) { this.taskOwner.playSound(SoundEvents.PLAYER_BURP, 1, 1); this.taskOwner.addHunger((itemstack1.getItem().getFoodProperties().getNutrition() * 10 * itemstack1.getCount())); for(Pair<MobEffectInstance, Float> pair : itemstack1.getItem().getFoodProperties().getEffects()) { if (pair.getFirst() != null && this.taskOwner.level.random.nextFloat() < pair.getSecond()) { this.taskOwner.addEffect(new MobEffectInstance(pair.getFirst())); } } return false; } if (!PotionUtils.getMobEffects(itemstack1).isEmpty()) { this.taskOwner.playSound(SoundEvents.PLAYER_BURP, 1, 1); this.taskOwner.addHunger(10); for(MobEffectInstance effectinstance : PotionUtils.getMobEffects(itemstack1)) { if (effectinstance.getEffect().isInstantenous()) { effectinstance.getEffect().applyInstantenousEffect(this.taskOwner, this.taskOwner, this.taskOwner, effectinstance.getAmplifier(), 1.0D); } else { this.taskOwner.addEffect(new MobEffectInstance(effectinstance)); } } return false; } this.taskOwner.spawnAtLocation(itemstack, 0.2f); return true; } } } else { int j = this.targetInventory.getContainerSize(); for (int k = 0; k < j; ++k) { ItemStack itemstack = this.targetInventory.getItem(k); if (!itemstack.isEmpty() && canExtractItemFromSlot(this.targetInventory, itemstack, k, enumfacing)) { ItemStack itemstack1 = itemstack.copy(); this.targetInventory.setItem(k, ItemStack.EMPTY); this.taskOwner.setAnimation(EntityBear.ATTACK_SWIPE); if (itemstack1.getItem().isEdible()) { this.taskOwner.playSound(SoundEvents.PLAYER_BURP, 1, 1); this.taskOwner.addHunger((itemstack1.getItem().getFoodProperties().getNutrition() * 10 * itemstack1.getCount())); for(Pair<MobEffectInstance, Float> pair : itemstack1.getItem().getFoodProperties().getEffects()) { if (pair.getFirst() != null && this.taskOwner.level.random.nextFloat() < pair.getSecond()) { this.taskOwner.addEffect(new MobEffectInstance(pair.getFirst())); } } return false; } if (!PotionUtils.getMobEffects(itemstack1).isEmpty()) { this.taskOwner.playSound(SoundEvents.GENERIC_DRINK, 1, 1); this.taskOwner.addHunger(10); for(MobEffectInstance effectinstance : PotionUtils.getMobEffects(itemstack1)) { if (effectinstance.getEffect().isInstantenous()) { effectinstance.getEffect().applyInstantenousEffect(this.taskOwner, this.taskOwner, this.taskOwner, effectinstance.getAmplifier(), 1.0D); } else { this.taskOwner.addEffect(new MobEffectInstance(effectinstance)); } } return false; } if (!(itemstack1.getItem().isEdible()) || !PotionUtils.getMobEffects(itemstack).isEmpty()) { this.taskOwner.spawnAtLocation(itemstack, 0.2f); } else { this.taskOwner.playSound(SoundEvents.PLAYER_BURP, 1, 1); return false; } return true; } } } } return false; } private static Container getInventoryAtPosition(Level worldIn, BlockPos pos) { Container iinventory = null; BlockState state = worldIn.getBlockState(pos); if (worldIn.getBlockEntity(pos) != null) { BlockEntity tileentity = worldIn.getBlockEntity(pos); if (tileentity instanceof Container) { iinventory = (Container)tileentity; /*if (iinventory instanceof ChestTileEntity && block instanceof ChestBlock) { iinventory = (Container) ((ChestBlock)block).getContainer(worldIn.getBlockState(pos), worldIn, pos); }*/ } } return iinventory; } private static boolean isInventoryEmpty(Container inventoryIn, Direction side) { if (inventoryIn instanceof WorldlyContainer) { WorldlyContainer isidedinventory = (WorldlyContainer)inventoryIn; int[] aint = isidedinventory.getSlotsForFace(side); for (int i : aint) { if (!isidedinventory.getItem(i).isEmpty()) { return false; } } } else { int j = inventoryIn.getContainerSize(); for (int k = 0; k < j; ++k) { if (!inventoryIn.getItem(k).isEmpty()) { return false; } } } return true; } private static boolean canExtractItemFromSlot(Container inventoryIn, ItemStack stack, int index, Direction side) { return !(inventoryIn instanceof WorldlyContainer) || ((WorldlyContainer)inventoryIn).canTakeItemThroughFace(index, stack, side); } private BlockPos getNearbyInventories(BlockPos roomCenter) { int X = 15; int Y = 3; //List<BlockPos> inventories = new ArrayList<>(); for (BlockPos blockpos : BlockPos.betweenClosed(roomCenter.offset(-X, -Y, -X), roomCenter.offset(X, Y, X))) { if (this.taskOwner.level.getBlockEntity(blockpos) != null && getInventoryAtPosition(this.taskOwner.level, blockpos) != null) { if (!isInventoryEmpty(getInventoryAtPosition(this.taskOwner.level, blockpos), Direction.UP)) { this.targetInventory = getInventoryAtPosition(this.taskOwner.level, blockpos); return blockpos; // For some bizarre reason, the blockPos inside the array changes once it exits the loop, // so yeah, returning the first inventory instead. The code remains commented just in case I ever figure this one out //inventories.add((BlockPos)blockpos); } } } return null; /*if (inventories.isEmpty()) { return null; } return inventories.get(this.taskOwner.getRandom().nextInt(Math.max(inventories.size() - 1, 1)));*/ } }
11,925
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
WhaleSwimmingGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/WhaleSwimmingGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.world.entity.ai.behavior.BehaviorUtils; import net.minecraft.world.entity.ai.goal.RandomSwimmingGoal; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.phys.Vec3; import untamedwilds.entity.mammal.EntityBaleenWhale; import javax.annotation.Nullable; public class WhaleSwimmingGoal extends RandomSwimmingGoal { private final EntityBaleenWhale taskOwner; public WhaleSwimmingGoal(EntityBaleenWhale entity) { super(entity, 1.0D, 20); this.taskOwner = entity; } @Nullable protected Vec3 getPosition() { Vec3 vector3d = BehaviorUtils.getRandomSwimmablePos(this.taskOwner, 10, 7); int offset = 5 + this.taskOwner.getRandom().nextInt(7) - 4; //for(int i = 0; vector3d != null && !this.taskOwner.level.getBlockState(new BlockPos(vector3d)).isPathfindable(this.taskOwner.level, new BlockPos(vector3d), PathComputationType.WATER) && i++ < 10; vector3d = BehaviorUtils.getRandomSwimmablePos(this.taskOwner, 10, 7)) { //} if (vector3d != null) { if (this.taskOwner.level.canSeeSky(this.taskOwner.blockPosition())) { //this.taskOwner.level.setBlock(new BlockPos(vector3d.x(), this.taskOwner.level.getHeight(Heightmap.Types.WORLD_SURFACE, (int)vector3d.x(), (int)vector3d.z()) - offset, vector3d.z()), Blocks.SEAGRASS.defaultBlockState(), 1); return new Vec3(vector3d.x(), this.taskOwner.level.getHeight(Heightmap.Types.WORLD_SURFACE, (int)vector3d.x(), (int)vector3d.z()) - offset, vector3d.z()); } //this.taskOwner.level.setBlock(new BlockPos(vector3d.x(), this.taskOwner.level.getHeight(Heightmap.Types.WORLD_SURFACE, (int)vector3d.x(), (int)vector3d.z()) - offset, vector3d.z()), Blocks.SEAGRASS.defaultBlockState(), 1); return vector3d.add(0, -offset, 0); } return null; } }
1,938
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SpitterTerritorialityGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/SpitterTerritorialityGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ai.target.HuntMobTarget; import untamedwilds.entity.relict.EntitySpitter; import javax.annotation.Nullable; import java.util.List; import java.util.function.Predicate; public class SpitterTerritorialityGoal<T extends LivingEntity> extends HuntMobTarget<T> { private final int executionChance; private final float threshold; public SpitterTerritorialityGoal(ComplexMob creature, Class<T> classTarget, boolean checkSight) { this(creature, classTarget, 300, checkSight, 0, null); } public SpitterTerritorialityGoal(ComplexMob creature, Class<T> classTarget, int chance, boolean checkSight, float threshold, final Predicate<LivingEntity> targetSelector) { super(creature, classTarget, checkSight,200, false, targetSelector); this.executionChance = chance; this.threshold = threshold; } protected boolean isValidTarget(LivingEntity entity, @Nullable Predicate<LivingEntity> predicate) { if (!(entity instanceof EntitySpitter) || ((EntitySpitter) entity).getGender() != ((EntitySpitter) this.mob).getGender() || entity.isBaby() || entity.equals(this.mob) || ((EntitySpitter) this.mob).isTame() || (predicate != null && !predicate.test(entity)) || entity.getHealth() / entity.getMaxHealth() < threshold) { return false; } return canAttack(entity, TargetingConditions.forCombat().range(getFollowDistance())); } @Override public boolean canUse() { if (this.mob.isBaby() || this.mob.getRandom().nextInt(this.executionChance) != 0) { return false; } List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.mob.getBoundingBox().inflate(this.getFollowDistance(), 12.0D, this.getFollowDistance()), this.targetEntitySelector); if (list.isEmpty()) return false; list.sort(this.sorter); this.targetMob = list.get(0); return true; } }
2,154
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
BisonTerritorialityFight.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/BisonTerritorialityFight.java
package untamedwilds.entity.ai.unique; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.phys.AABB; import untamedwilds.entity.mammal.EntityBison; import untamedwilds.util.EntityUtils; import java.util.EnumSet; import java.util.List; import java.util.Random; public class BisonTerritorialityFight extends Goal { private final EntityBison taskOwner; private EntityBison targetAnimal; private final double moveSpeed; private int charge; private boolean isDone = false; private Goal slaveGoal; public BisonTerritorialityFight(EntityBison entityIn, double speedIn) { this.taskOwner = entityIn; this.moveSpeed = speedIn; this.setFlags(EnumSet.of(Flag.MOVE, Flag.TARGET, Flag.LOOK)); } @Override public boolean canUse() { if (!EntityUtils.hasFullHealth(this.taskOwner) || this.taskOwner.isBaby() || !this.taskOwner.canMove() || !this.taskOwner.isMale()) { return false; } if (this.taskOwner.getRandom().nextInt(400) != 0) return false; List<? extends EntityBison> list = this.taskOwner.level.getEntitiesOfClass(this.taskOwner.getClass(), this.taskOwner.getBoundingBox().inflate(8.0D, 4.0D, 8.0D)); EntityBison target_animal = null; double d0 = Double.MAX_VALUE; for (EntityBison potential_targets : list) { if (!potential_targets.equals(this.taskOwner) && !potential_targets.isBaby() && (potential_targets.getVariant() == this.taskOwner.getVariant()) && potential_targets.isMale() && potential_targets.canMove()) { double d1 = this.taskOwner.distanceToSqr(potential_targets); if (d1 <= d0) { d0 = d1; target_animal = potential_targets; } } } if (target_animal == null) { return false; } else { this.targetAnimal = target_animal; this.isDone = false; this.slaveGoal = new TerritorialFightingGoal_slave(this.targetAnimal, 1.4F, this.taskOwner); return true; } } @Override public void start() { EntityUtils.spawnParticlesOnEntity(this.taskOwner.level, this.taskOwner, ParticleTypes.ANGRY_VILLAGER, 10, 1); EntityUtils.spawnParticlesOnEntity(this.targetAnimal.level, this.targetAnimal, ParticleTypes.ANGRY_VILLAGER, 10, 1); this.charge = 40; this.targetAnimal.goalSelector.addGoal(1, this.slaveGoal); this.taskOwner.getLookControl().setLookAt(this.targetAnimal); this.taskOwner.setAnimation(EntityBison.ATTACK_THREATEN); this.taskOwner.setSprinting(true); if (!this.targetAnimal.canMove()) { this.targetAnimal.setSitting(false); this.targetAnimal.setSleeping(false); } } public boolean canContinueToUse() { return !this.isDone && EntityUtils.hasFullHealth(this.taskOwner); } public void tick() { this.taskOwner.getLookControl().setLookAt(this.targetAnimal); if (charge > 0) { if (--charge == 0) { this.taskOwner.getNavigation().moveTo(this.targetAnimal, this.moveSpeed * 1.2F); } } else { // AABB checking AABB offset_box = this.taskOwner.getBoundingBox().move(Math.cos(Math.toRadians(this.taskOwner.getYRot() + 90)) * 1.2, 0, Math.sin(Math.toRadians(this.taskOwner.getYRot() + 90)) * 1.2); List<LivingEntity> entitiesHit = this.taskOwner.getLevel().getNearbyEntities(LivingEntity.class, TargetingConditions.forCombat(), this.taskOwner, offset_box); for (LivingEntity entityHit : entitiesHit) { if (!entityHit.equals(this.taskOwner) && this.taskOwner.hasLineOfSight(entityHit)) { if (entityHit.equals(this.targetAnimal)) { Random rand = this.taskOwner.getRandom(); ServerLevel world = (ServerLevel) this.taskOwner.getLevel(); world.sendParticles(ParticleTypes.SMOKE, rand.nextFloat((float)offset_box.minX, (float)offset_box.maxX), rand.nextFloat((float)offset_box.minY, (float)offset_box.maxY), rand.nextFloat((float)offset_box.minZ, (float)offset_box.maxZ), 10, 0, 0, 0, 0.05); this.targetAnimal.hurt(DamageSource.GENERIC, 2); this.isDone = true; } } } } } public void stop() { this.targetAnimal.goalSelector.removeGoal(this.slaveGoal); this.charge = 0; this.taskOwner.setSprinting(false); this.taskOwner.level.playSound(null, this.taskOwner.getX(), this.taskOwner.getY(), this.taskOwner.getZ(), SoundEvents.GOAT_RAM_IMPACT, SoundSource.NEUTRAL, 1.0F, 1.0F); this.taskOwner.setDeltaMovement(this.taskOwner.getDeltaMovement().scale(-0.15F)); } public static class TerritorialFightingGoal_slave extends Goal { private final EntityBison taskOwner; private final EntityBison targetAnimal; private final double moveSpeed; private int charge; private boolean isDone = false; public TerritorialFightingGoal_slave(EntityBison entityIn, double speedIn, EntityBison targetAnimal) { this.taskOwner = entityIn; this.moveSpeed = speedIn; this.targetAnimal = targetAnimal; this.setFlags(EnumSet.of(Flag.MOVE, Flag.TARGET, Flag.LOOK)); } @Override public boolean canUse() { return !this.taskOwner.isBaby() && this.taskOwner.canMove() && this.taskOwner.isMale(); } @Override public void start() { this.charge = 40; this.isDone = false; this.taskOwner.getLookControl().setLookAt(this.targetAnimal); this.taskOwner.setAnimation(EntityBison.ATTACK_THREATEN); this.taskOwner.setSprinting(true); if (!this.targetAnimal.canMove()) { this.targetAnimal.setSitting(false); this.targetAnimal.setSleeping(false); } } public boolean canContinueToUse() { return !this.isDone; } public void tick() { this.taskOwner.getLookControl().setLookAt(this.targetAnimal); if (charge > 0) { if (--charge == 0) { this.taskOwner.getNavigation().moveTo(this.targetAnimal, this.moveSpeed * 1.2F); } } else { // AABB checking AABB offset_box = this.taskOwner.getBoundingBox().move(Math.cos(Math.toRadians(this.taskOwner.getYRot() + 90)) * 1.2, 0, Math.sin(Math.toRadians(this.taskOwner.getYRot() + 90)) * 1.2); List<LivingEntity> entitiesHit = this.taskOwner.getLevel().getNearbyEntities(LivingEntity.class, TargetingConditions.forCombat(), this.taskOwner, offset_box); for (LivingEntity entityHit : entitiesHit) { if (!entityHit.equals(this.taskOwner) && this.taskOwner.hasLineOfSight(entityHit)) { if (entityHit.equals(this.targetAnimal)) { Random rand = this.taskOwner.getRandom(); ServerLevel world = (ServerLevel) this.taskOwner.getLevel(); world.sendParticles(ParticleTypes.SMOKE, rand.nextFloat((float)offset_box.minX, (float)offset_box.maxX), rand.nextFloat((float)offset_box.minY, (float)offset_box.maxY), rand.nextFloat((float)offset_box.minZ, (float)offset_box.maxZ), 10, 0, 0, 0, 0.05); this.targetAnimal.hurt(DamageSource.mobAttack(null), 2); this.isDone = true; } } } } } public void stop() { this.charge = 0; this.taskOwner.setSprinting(false); this.taskOwner.setDeltaMovement(this.taskOwner.getDeltaMovement().scale(-0.15F)); } } }
8,407
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CatfishGarbageBinGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/unique/CatfishGarbageBinGoal.java
package untamedwilds.entity.ai.unique; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.phys.AABB; import untamedwilds.entity.fish.EntityCatfish; import java.util.Comparator; import java.util.EnumSet; import java.util.List; public class CatfishGarbageBinGoal extends Goal { private final EntityCatfish taskOwner; private final ClosestSorter sorter; private final int distance; private ItemEntity targetItem; private final int executionChance; public CatfishGarbageBinGoal(EntityCatfish entityIn, int distance) { this(entityIn, distance, 100); } public CatfishGarbageBinGoal(EntityCatfish entityIn, int distance, int chance) { this.taskOwner = entityIn; this.sorter = new ClosestSorter(entityIn); this.distance = distance; this.executionChance = chance; this.setFlags(EnumSet.of(Flag.MOVE, Flag.TARGET)); } public boolean canUse() { if (this.taskOwner.isBaby() || this.taskOwner.isSleeping()) { return false; } if (this.taskOwner.getRandom().nextInt(this.executionChance) != 0) { return false; } List<ItemEntity> list = this.taskOwner.level.getEntitiesOfClass(ItemEntity.class, this.getTargettableArea(distance)); list.removeIf((ItemEntity item) -> !item.getItem().isEdible()); if (!list.isEmpty()) { list.sort(this.sorter); this.targetItem = list.get(0); return true; } return false; } private AABB getTargettableArea(double targetDistance) { return this.taskOwner.getBoundingBox().inflate(targetDistance, 4.0D, targetDistance); } @Override public void start() { this.taskOwner.getNavigation().moveTo(this.targetItem.getX(), this.targetItem.getY(), this.targetItem.getZ(), 1D); } @Override public boolean canContinueToUse() { if (this.targetItem == null || !this.targetItem.isAlive()) { return false; } else if (!this.taskOwner.canMove()) { return false; } return !this.taskOwner.isPathFinding(); } @Override public void tick() { double distance = Math.sqrt(Math.pow(this.taskOwner.getX() - this.targetItem.getX(), 2.0D) + Math.pow(this.taskOwner.getZ() - this.targetItem.getZ(), 2.0D)); if (distance < 1.5D) { this.targetItem.getItem().shrink(1); } if(this.taskOwner.getNavigation().isDone()){ stop(); } this.taskOwner.getNavigation().moveTo(this.targetItem.getX(), this.targetItem.getY(), this.targetItem.getZ(), 1D); } public static class ClosestSorter implements Comparator<Entity> { private final Entity entity; private ClosestSorter(Entity entityIn) { this.entity = entityIn; } public int compare(Entity entity_1, Entity entity_2) { double dist_1 = this.entity.distanceToSqr(entity_1); double dist_2 = this.entity.distanceToSqr(entity_2); if (dist_1 < dist_2) { return -1; } else { return dist_1 > dist_2 ? 1 : 0; } } } }
3,394
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
GuardPositionTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/GuardPositionTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.TamableAnimal; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.phys.AABB; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ComplexMobTerrestrial; import javax.annotation.Nullable; import java.util.Comparator; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class GuardPositionTarget<T extends LivingEntity> extends TargetGoal { protected BlockPos guardPos; protected final Class<T> targetClass; protected final Sorter sorter; protected Predicate<? super T> targetEntitySelector; public GuardPositionTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight, boolean isCannibal, final Predicate<LivingEntity> targetSelector) { super(creature, checkSight, true); this.targetClass = classTarget; this.sorter = new Sorter(creature); this.setFlags(EnumSet.of(Flag.TARGET, Flag.MOVE, Flag.JUMP)); this.targetEntitySelector = entity -> isValidTarget(entity, targetSelector); } protected boolean isValidTarget(LivingEntity entity, @Nullable Predicate<LivingEntity> predicate) { if (entity instanceof Creeper || entity.equals(this.mob) || (predicate != null && !predicate.test(entity))) { return false; } if (entity instanceof TamableAnimal tamable) { if (tamable.isTame()) { // TODO: Logic to decide which mobs belong to an enemy "team" return false; } } return canAttack(entity, TargetingConditions.forCombat().range(getFollowDistance())); } public boolean canUse() { if (this.mob.isBaby() || this.mob.getHealth() < this.mob.getMaxHealth() / 3) { return false; } if (this.mob instanceof ComplexMob cmob) { if (!cmob.isTame() || cmob.getCommandInt() != 3) return false; } if (this.guardPos == null) this.guardPos = this.mob.blockPosition(); List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.getTargettableArea(this.getFollowDistance()), this.targetEntitySelector); if (list.isEmpty() && this.guardPos != null) { this.mob.getNavigation().moveTo(this.guardPos.getX(), this.guardPos.getY(), this.guardPos.getZ(), 1); if (this.mob.distanceToSqr(this.guardPos.getX(), this.guardPos.getY(), this.guardPos.getZ()) < 2) { this.mob.getNavigation().stop(); if (this.mob instanceof ComplexMob cmob) cmob.setSitting(true); } // TODO: Code to go back to position and sit there return false; } list.sort(this.sorter); this.targetMob = list.get(0); return true; } AABB getTargettableArea(double targetDistance) { return this.mob.getBoundingBox().inflate(targetDistance, 4.0D, targetDistance); } public void start() { if (!this.mob.getNavigation().isDone()) this.mob.getNavigation().stop(); if (this.mob instanceof ComplexMob) ((ComplexMob)this.mob).huntingCooldown = 6000; this.mob.setTarget(this.targetMob); super.start(); } public boolean canContinueToUse() { return super.canContinueToUse(); } public static class Sorter implements Comparator<Entity> { private final Entity entity; private Sorter(Entity entityIn) { this.entity = entityIn; } public int compare(Entity entity_1, Entity entity_2) { double dist_1 = this.entity.distanceToSqr(entity_1); double dist_2 = this.entity.distanceToSqr(entity_2); if (dist_1 < dist_2) { return -1; } else { return dist_1 > dist_2 ? 1 : 0; } } } }
4,235
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
AngrySleeperTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/AngrySleeperTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.player.Player; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ComplexMobTerrestrial; import untamedwilds.entity.ISpecies; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class AngrySleeperTarget<T extends LivingEntity> extends TargetGoal { protected final Class<T> targetClass; protected final int targetChance; protected LivingEntity target; protected ComplexMobTerrestrial taskOwner; protected Predicate<T> targetEntitySelector; private int runningTicks; public AngrySleeperTarget(ComplexMobTerrestrial entityIn, Class<T> targetClassIn, boolean checkSight) { this(entityIn, targetClassIn, checkSight, false); } public AngrySleeperTarget(ComplexMobTerrestrial entityIn, Class<T> targetClassIn, boolean checkSight, boolean nearbyOnlyIn) { this(entityIn, targetClassIn, 4, checkSight, nearbyOnlyIn); } public AngrySleeperTarget(ComplexMobTerrestrial entityIn, Class<T> targetClassIn, int targetChanceIn, boolean checkSight, boolean nearbyOnlyIn) { super(entityIn, checkSight, nearbyOnlyIn); this.targetClass = targetClassIn; this.targetChance = targetChanceIn; this.setFlags(EnumSet.of(Flag.TARGET)); this.runningTicks = 1000; this.taskOwner = entityIn; this.targetEntitySelector = entity -> { if (entity instanceof Creeper || ComplexMob.getEcoLevel(this.taskOwner) > ComplexMob.getEcoLevel(entity) * 2) { return false; } if (this.taskOwner.getClass() == entity.getClass()) { if (this.taskOwner instanceof ISpecies && entity instanceof ISpecies) { ComplexMob attacker = this.taskOwner; ComplexMob defender = ((ComplexMob)entity); if (attacker.getVariant() == defender.getVariant()) { return false; } } } if (entity instanceof Player player) { if (player.isSteppingCarefully() || player.isCreative() || player.isSpectator()) return false; } return TargetingConditions.forCombat().test(this.taskOwner, entity) && this.canAttack(entity, TargetingConditions.DEFAULT); }; } public boolean canUse() { if (!ConfigGamerules.angrySleepers.get() || this.taskOwner.isBaby() || !this.taskOwner.isSleeping() || this.taskOwner.isTame() || this.taskOwner.forceSleep != 0) { return false; } List<LivingEntity> list = this.mob.level.getEntitiesOfClass(LivingEntity.class, this.mob.getBoundingBox().inflate(6.0D, 4.0D, 6.0D), (input) -> this.targetEntitySelector.test((T) input)); if (!list.isEmpty()) { LivingEntity player = list.get(0); this.taskOwner.setSleeping(false); this.target = player; } return true; } public void start() { this.taskOwner.setTarget(this.target); this.taskOwner.forceSleep = -300; super.start(); } public boolean canContinueToUse() { this.runningTicks--; if (this.runningTicks < 1) return false; return super.canContinueToUse(); } }
3,638
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
HuntMobTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/HuntMobTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.phys.AABB; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ComplexMobTerrestrial; import javax.annotation.Nullable; import java.util.Comparator; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class HuntMobTarget<T extends LivingEntity> extends TargetGoal { protected final Class<T> targetClass; protected final Sorter sorter; protected Predicate<? super T> targetEntitySelector; private final int threshold; private final boolean isCannibal; public HuntMobTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight, boolean isCannibal, final Predicate<LivingEntity> targetSelector) { this(creature, classTarget, checkSight, 200, isCannibal, targetSelector); } public HuntMobTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight, int hungerThreshold, boolean isCannibal, final Predicate<LivingEntity> targetSelector) { super(creature, checkSight, true); this.targetClass = classTarget; this.sorter = new Sorter(creature); this.setFlags(EnumSet.of(Flag.TARGET)); this.threshold = hungerThreshold; this.isCannibal = isCannibal; this.targetEntitySelector = entity -> isValidTarget(entity, targetSelector); } protected boolean isValidTarget(LivingEntity entity, @Nullable Predicate<LivingEntity> predicate) { if (entity instanceof Creeper || entity.equals(this.mob) || (!ConfigGamerules.attackUndead.get() && entity.getMobType() == MobType.UNDEAD) || (entity instanceof ComplexMob cmob && !cmob.canBeTargeted()) || (predicate != null && !predicate.test(entity))) { return false; } if (!this.isCannibal && this.mob.getClass() == entity.getClass() && this.mob instanceof ComplexMob attacker && entity instanceof ComplexMob defender) { if (attacker.getVariant() == defender.getVariant()) { return false; } } return canAttack(entity, TargetingConditions.forCombat().range(getFollowDistance())); } public boolean canUse() { if (this.mob.isBaby() || this.mob.getHealth() < this.mob.getMaxHealth() / 3) { return false; } if (this.mob instanceof ComplexMob) { if (((ComplexMob)this.mob).huntingCooldown != 0) return false; if (this.mob instanceof ComplexMobTerrestrial tamed) { if (tamed.isTame() || tamed.getHunger() > this.threshold) return false; } } List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.getTargettableArea(this.getFollowDistance()), this.targetEntitySelector); if (list.isEmpty()) return false; list.sort(this.sorter); this.targetMob = list.get(0); return true; } AABB getTargettableArea(double targetDistance) { return this.mob.getBoundingBox().inflate(targetDistance, 4.0D, targetDistance); } public void start() { if (!this.mob.getNavigation().isDone()) this.mob.getNavigation().stop(); if (this.mob instanceof ComplexMob) ((ComplexMob)this.mob).huntingCooldown = 6000; this.mob.setTarget(this.targetMob); super.start(); } public boolean canContinueToUse() { return super.canContinueToUse(); } public static class Sorter implements Comparator<Entity> { private final Entity entity; private Sorter(Entity entityIn) { this.entity = entityIn; } public int compare(Entity entity_1, Entity entity_2) { double dist_1 = this.entity.distanceToSqr(entity_1); double dist_2 = this.entity.distanceToSqr(entity_2); if (dist_1 < dist_2) { return -1; } else { return dist_1 > dist_2 ? 1 : 0; } } } }
4,395
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
HuntWeakerTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/HuntWeakerTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import javax.annotation.Nullable; import java.util.List; import java.util.function.Predicate; public class HuntWeakerTarget<T extends LivingEntity> extends HuntMobTarget<T> { private final int executionChance; public HuntWeakerTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight) { this(creature, classTarget, 300, checkSight, null); } public HuntWeakerTarget(ComplexMob creature, Class<T> classTarget, int chance, boolean checkSight, final Predicate<LivingEntity> targetSelector) { super(creature, classTarget, checkSight,200, false, targetSelector); this.executionChance = chance; } protected boolean isValidTarget(LivingEntity entity, @Nullable Predicate<LivingEntity> predicate) { if (entity instanceof Creeper || entity.equals(this.mob) || (!ConfigGamerules.attackUndead.get() && entity.getMobType() == MobType.UNDEAD) || entity.isVehicle() || (predicate != null && !predicate.test(entity)) || entity.getHealth() / entity.getMaxHealth() > 0.8) { return false; } if (ComplexMob.getEcoLevel(entity) < ComplexMob.getEcoLevel(this.mob) && this.mob.getClass() == entity.getClass() && this.mob instanceof ComplexMob attacker && entity instanceof ComplexMob defender) { if (attacker.getVariant() == defender.getVariant()) { return false; } } return canAttack(entity, TargetingConditions.forCombat().range(getFollowDistance())); } @Override public boolean canUse() { if (this.mob.isBaby() || this.mob.getRandom().nextInt(this.executionChance) != 0) { return false; } List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.mob.getBoundingBox().inflate(this.getFollowDistance(), 12.0D, this.getFollowDistance()), this.targetEntitySelector); if (list.isEmpty()) return false; list.sort(this.sorter); this.targetMob = list.get(0); return true; } }
2,351
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartOwnerHurtTargetGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/SmartOwnerHurtTargetGoal.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.TamableAnimal; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.animal.horse.Horse; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.monster.Ghast; import net.minecraft.world.entity.player.Player; import untamedwilds.entity.ComplexMob; import java.util.EnumSet; public class SmartOwnerHurtTargetGoal extends TargetGoal { private final ComplexMob tameable; private LivingEntity attacker; private int timestamp; public SmartOwnerHurtTargetGoal(ComplexMob entityIn) { super(entityIn, false); this.tameable = entityIn; this.setFlags(EnumSet.of(Flag.TARGET)); } public boolean canUse() { if (this.tameable.isTame() && !this.tameable.isOrderedToSit()) { LivingEntity livingentity = this.tameable.getOwner(); if (livingentity == null) { return false; } else { this.attacker = livingentity.getLastHurtMob(); int i = livingentity.getLastHurtMobTimestamp(); return i != this.timestamp && this.canAttack(this.attacker, TargetingConditions.DEFAULT) && this.shouldAttackEntity(this.attacker, livingentity); } } else { return false; } } public void start() { this.mob.setTarget(this.attacker); LivingEntity livingentity = this.tameable.getOwner(); if (livingentity != null) { this.timestamp = livingentity.getLastHurtMobTimestamp(); } super.start(); } // Taken from WolfEntity private boolean shouldAttackEntity(LivingEntity target, LivingEntity owner) { if (!(target instanceof Creeper) && !(target instanceof Ghast)) { if (target instanceof TamableAnimal tamableTarget) { if (tamableTarget.isTame() && tamableTarget.getOwner() == owner) { return false; } } if (target instanceof Player && owner instanceof Player && !owner.canAttack(owner)) { return false; } else return !(target instanceof Horse) || !((Horse) target).isTamed(); } return false; } }
2,429
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartHurtByTargetGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/SmartHurtByTargetGoal.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.goal.target.HurtByTargetGoal; import java.util.EnumSet; // Only difference between SmartHurtByTargetGoal and HurtByTargetGoal is that this class // automatically alerts others when the hurt mod is a baby public class SmartHurtByTargetGoal extends HurtByTargetGoal { public SmartHurtByTargetGoal(PathfinderMob p_26039_, Class<?>... p_26040_) { super(p_26039_, p_26040_); this.setFlags(EnumSet.of(Goal.Flag.TARGET)); } public void start() { if (this.mob.isBaby()) this.alertOthers(); super.start(); } }
739
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
DontThreadOnMeTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/DontThreadOnMeTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import javax.annotation.Nullable; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class DontThreadOnMeTarget<T extends LivingEntity> extends TargetGoal { protected final Class<T> targetClass; protected Predicate<T> targetEntitySelector; private int runningTicks; public DontThreadOnMeTarget(Mob entityIn, Class<T> targetClassIn, boolean checkSight) { this(entityIn, targetClassIn, checkSight, false); } public DontThreadOnMeTarget(Mob entityIn, Class<T> targetClassIn, boolean checkSight, boolean nearbyOnlyIn) { super(entityIn, checkSight, nearbyOnlyIn); this.targetClass = targetClassIn; this.setFlags(EnumSet.of(Goal.Flag.TARGET)); this.targetEntitySelector = entity -> isValidTarget(entity, null); } protected boolean isValidTarget(LivingEntity entity, @Nullable Predicate<LivingEntity> predicate) { if (entity instanceof Creeper || entity.equals(this.mob) || (!ConfigGamerules.attackUndead.get() && entity.getMobType() == MobType.UNDEAD) || (predicate != null && !predicate.test(entity))) { return false; } if (this.mob.getClass() == entity.getClass() && this.mob instanceof ComplexMob attacker && entity instanceof ComplexMob defender) { if (attacker.getVariant() == defender.getVariant()) { return false; } } return entity.getBoundingBox().intersects(this.mob.getBoundingBox()) && canAttack(entity, TargetingConditions.forCombat().range(getFollowDistance())); } public boolean canUse() { if (!ConfigGamerules.contactAgression.get()) { return false; } else { List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.mob.getBoundingBox().inflate(1F), this.targetEntitySelector); if (list.isEmpty()) { return false; } else { this.targetMob = list.get(0); return true; } } } public void start() { this.mob.setTarget(this.targetMob); this.runningTicks = 60; super.start(); } public boolean canContinueToUse() { this.runningTicks--; if (this.runningTicks < 1) { this.mob.setTarget(null); return false; } return super.canContinueToUse(); } }
2,906
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
BeAnAssTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/BeAnAssTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.monster.RangedAttackMob; import net.minecraft.world.phys.AABB; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ComplexMobTerrestrial; import untamedwilds.entity.mammal.EntityCamel; import java.util.Comparator; import java.util.EnumSet; import java.util.List; import java.util.function.Predicate; public class BeAnAssTarget<T extends LivingEntity> extends TargetGoal { protected final Class<T> targetClass; protected final Sorter sorter; protected Predicate<? super T> targetEntitySelector; protected T targetEntity; public BeAnAssTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight, final Predicate<? super T> targetSelector) { super(creature, checkSight, true); this.targetClass = classTarget; this.sorter = new Sorter(creature); this.setFlags(EnumSet.of(Flag.TARGET)); this.targetEntitySelector = (Predicate<T>) entity -> { if (targetSelector != null && !targetSelector.test(entity)) { return false; } return this.canAttack(entity, TargetingConditions.DEFAULT); }; } public boolean canUse() { if (!(this.mob instanceof EntityCamel)) { UntamedWilds.LOGGER.warn("Trying to run BeAnAssTarget Goal on a mob without a ranged attack"); return false; } if (this.mob.getRandom().nextInt(200) != 0 || this.mob.isBaby() || this.mob.getHealth() < this.mob.getMaxHealth() / 2) { return false; } if (this.mob instanceof ComplexMob complexMob) { if (complexMob.isTame()) { return false; } } List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.getTargetableArea(this.getFollowDistance()), this.targetEntitySelector); list.removeIf((Predicate<LivingEntity>) this::shouldRemoveTarget); if (list.isEmpty()) { return false; } else { list.sort(this.sorter); this.targetEntity = list.get(0); if (this.mob instanceof ComplexMob) { ((ComplexMob)this.mob).huntingCooldown = 6000; } return true; } } AABB getTargetableArea(double targetDistance) { return this.mob.getBoundingBox().inflate(targetDistance, 4.0D, targetDistance); } public void start() { this.mob.getLookControl().setLookAt(this.targetEntity); if (this.mob instanceof EntityCamel camel) { camel.performRangedAttack(this.targetEntity, 0.5F); } //this.mob.setTarget(this.targetEntity); super.start(); } public boolean shouldRemoveTarget(LivingEntity entity) { if (entity instanceof Creeper) { return false; // Hardcoded Creepers out because they will absolutely destroy wildlife if targeted } if (entity instanceof ComplexMob ctarget) { return (mob.getClass() == entity.getClass() && ((ComplexMob)mob).getVariant() == ctarget.getVariant()) || !ctarget.canBeTargeted(); } return false; } public static class Sorter implements Comparator<Entity> { private final Entity entity; private Sorter(Entity entityIn) { this.entity = entityIn; } public int compare(Entity entity_1, Entity entity_2) { double dist_1 = this.entity.distanceToSqr(entity_1); double dist_2 = this.entity.distanceToSqr(entity_2); if (dist_1 < dist_2) { return -1; } else { return dist_1 > dist_2 ? 1 : 0; } } } }
4,075
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ProtectChildrenTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/ProtectChildrenTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobType; import net.minecraft.world.entity.TamableAnimal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.monster.Creeper; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import javax.annotation.Nullable; import java.util.List; import java.util.function.Predicate; public class ProtectChildrenTarget<T extends LivingEntity> extends HuntMobTarget<T> { private Mob protectTarget; public ProtectChildrenTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight, final Predicate<LivingEntity> targetSelector) { super(creature, classTarget, checkSight,200, false, targetSelector); } protected boolean isValidTarget(LivingEntity entity, @Nullable Predicate<LivingEntity> predicate) { if (entity instanceof Creeper || entity.equals(this.mob) || (!ConfigGamerules.attackUndead.get() && entity.getMobType() == MobType.UNDEAD) || (predicate != null && !predicate.test(entity))) { return false; } if (ComplexMob.getEcoLevel(entity) < ComplexMob.getEcoLevel(this.mob) && this.mob.getClass() == entity.getClass() && this.mob instanceof ComplexMob attacker && entity instanceof ComplexMob defender) { if (attacker.getVariant() == defender.getVariant()) { return false; } } return canAttack(entity, TargetingConditions.forCombat().range(getFollowDistance())); } @Override public boolean canUse() { if (this.mob.isBaby() || (this.mob instanceof TamableAnimal tamable && tamable.isTame())) return false; if (this.mob instanceof ComplexMob temp) { for (Mob child : this.mob.level.getEntitiesOfClass(this.mob.getClass(), mob.getBoundingBox().inflate(8.0D, 4.0D, 8.0D))) { if (child.isBaby() && ((ComplexMob)child).getVariant() == temp.getVariant()) { this.protectTarget = child; List<T> list = this.mob.level.getEntitiesOfClass(this.targetClass, this.getTargettableArea(this.getFollowDistance()), this.targetEntitySelector); if (list.isEmpty()) { return false; } list.sort(this.sorter); this.targetMob = list.get(0); return true; } } } return false; } public boolean canContinueToUse() { if (this.protectTarget.distanceTo(this.mob) > 12) { this.mob.setTarget(null); this.targetMob = null; this.mob.getNavigation().moveTo(this.protectTarget, 1); return false; } return super.canContinueToUse(); } @Override protected double getFollowDistance() { return super.getFollowDistance() * 0.5D; } }
3,039
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
HuntPackMobTarget.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/HuntPackMobTarget.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import untamedwilds.entity.ComplexMob; import java.util.function.Predicate; public class HuntPackMobTarget<T extends LivingEntity> extends HuntMobTarget<T> { public HuntPackMobTarget(ComplexMob creature, Class<T> classTarget, boolean checkSight, int hungerThreshold, boolean onlyNearby, final Predicate<LivingEntity> targetSelector) { super(creature, classTarget, checkSight, hungerThreshold, false, null); } public void start() { this.mob.setTarget(this.targetMob); if (this.mob instanceof ComplexMob mob && mob.herd != null) { for (ComplexMob creature : mob.herd.creatureList) { creature.setTarget(this.targetMob); } } super.start(); } }
828
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
HurtPackByTargetGoal.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/target/HurtPackByTargetGoal.java
package untamedwilds.entity.ai.target; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import untamedwilds.entity.ComplexMob; import java.util.EnumSet; public class HurtPackByTargetGoal extends TargetGoal { private static final TargetingConditions field_220795_a = (TargetingConditions.DEFAULT); private boolean entityCallsForHelp; private int revengeTimerOld; private final Class<?>[] excludedReinforcementTypes; private Class<?>[] reinforcementTypes; public HurtPackByTargetGoal(PathfinderMob creatureIn, Class<?>... excludeReinforcementTypes) { super(creatureIn, true); this.excludedReinforcementTypes = excludeReinforcementTypes; this.setFlags(EnumSet.of(Goal.Flag.TARGET)); } public boolean canUse() { int i = this.mob.getLastHurtByMobTimestamp(); LivingEntity livingentity = this.mob.getLastHurtByMob(); if (i != this.revengeTimerOld && livingentity != null) { for(Class<?> oclass : this.excludedReinforcementTypes) { if (oclass.isAssignableFrom(livingentity.getClass())) { return false; } } return this.canAttack(livingentity, field_220795_a); } else { return false; } } public HurtPackByTargetGoal setAlertOthers(Class<?>... reinforcementTypes) { this.entityCallsForHelp = true; this.reinforcementTypes = reinforcementTypes; return this; } public void start() { this.mob.setTarget(this.mob.getLastHurtByMob()); this.targetMob = this.mob.getTarget(); this.revengeTimerOld = this.mob.getLastHurtByMobTimestamp(); this.unseenMemoryTicks = 300; if (this.entityCallsForHelp) { this.alertOthers(); } super.start(); } protected void alertOthers() { if (this.mob instanceof ComplexMob) { ComplexMob mob = (ComplexMob)this.mob; if (mob.herd != null) { for (ComplexMob creature : mob.herd.creatureList) { creature.setTarget(this.mob.getLastHurtByMob()); } } } } }
2,418
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartLandLookControl.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/control/look/SmartLandLookControl.java
package untamedwilds.entity.ai.control.look; import net.minecraft.util.Mth; import net.minecraft.world.entity.ai.control.SmoothSwimmingLookControl; import untamedwilds.entity.ComplexMob; public class SmartLandLookControl extends SmoothSwimmingLookControl { private final ComplexMob mob; private final int maxYRot; public SmartLandLookControl(ComplexMob entity, int maxYRotFromCenter) { super(entity, maxYRotFromCenter); this.maxYRot = maxYRotFromCenter; this.mob = entity; } public void tick() { if (!this.mob.canMove()) { if (this.lookAtCooldown > 0) { --this.lookAtCooldown; this.getYRotD().ifPresent((p_181134_) -> { this.mob.yHeadRot = this.rotateTowards(this.mob.yHeadRot, p_181134_ + 20.0F, this.yMaxRotSpeed); }); this.getXRotD().ifPresent((p_181132_) -> { this.mob.setXRot(this.rotateTowards(this.mob.getXRot(), p_181132_ + 10.0F, this.xMaxRotAngle)); }); } else { if (this.mob.getNavigation().isDone()) { this.mob.setXRot(this.rotateTowards(this.mob.getXRot(), 0.0F, 5.0F)); } this.mob.yHeadRot = this.rotateTowards(this.mob.yHeadRot, this.mob.yBodyRot, this.yMaxRotSpeed); } if (!this.mob.isNotMoving()) { float f = Mth.wrapDegrees(this.mob.yHeadRot - this.mob.yBodyRot); if (f < (float)(-this.maxYRot)) { this.mob.yBodyRot -= 4.0F; } else if (f > (float)this.maxYRot) { this.mob.yBodyRot += 4.0F; } } } } }
1,739
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartSwimmerLookControl.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/control/look/SmartSwimmerLookControl.java
package untamedwilds.entity.ai.control.look; import net.minecraft.world.entity.ai.control.SmoothSwimmingLookControl; import untamedwilds.entity.ComplexMob; public class SmartSwimmerLookControl extends SmoothSwimmingLookControl { private final ComplexMob mob; public SmartSwimmerLookControl(ComplexMob entity, int maxYRotFromCenter) { super(entity, maxYRotFromCenter); this.mob = entity; } public void tick() { if (/*!this.mob.isNotMoving() && */this.mob.canMove()) { super.tick(); } } }
554
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartSwimmingMoveControl.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/control/movement/SmartSwimmingMoveControl.java
package untamedwilds.entity.ai.control.movement; import net.minecraft.util.Mth; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.control.MoveControl; // Copied straight from the vanilla class public class SmartSwimmingMoveControl extends MoveControl { private final int maxTurnX; private final int maxTurnY; private final float inWaterSpeedModifier; private final float outsideWaterSpeedModifier; private final boolean applyGravity; public SmartSwimmingMoveControl(Mob entityIn, int maxTurnX, int maxTurnY, float waterSpeedFactor, float landSpeedFactor, boolean applyGravity) { super(entityIn); this.maxTurnX = maxTurnX; this.maxTurnY = maxTurnY; this.inWaterSpeedModifier = waterSpeedFactor; this.outsideWaterSpeedModifier = landSpeedFactor; this.applyGravity = applyGravity; } public void tick() { if (this.applyGravity && this.mob.isInWater()) { this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(0.0D, 0.005D, 0.0D)); } if (this.operation == MoveControl.Operation.MOVE_TO && !this.mob.getNavigation().isDone()) { double d0 = this.wantedX - this.mob.getX(); double d1 = this.wantedY - this.mob.getY(); double d2 = this.wantedZ - this.mob.getZ(); double d3 = d0 * d0 + d1 * d1 + d2 * d2; if (d3 < (double)2.5000003E-7F) { this.mob.setZza(0.0F); } else { float f = (float)(Mth.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F; this.mob.setYRot(this.rotlerp(this.mob.getYRot(), f, (float)this.maxTurnY)); this.mob.yBodyRot = this.mob.getYRot(); this.mob.yHeadRot = this.mob.getYRot(); float f1 = (float)(this.speedModifier * this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED)); if (this.mob.isInWater()) { this.mob.setSpeed(f1 * this.inWaterSpeedModifier); double d4 = Math.sqrt(d0 * d0 + d2 * d2); if (Math.abs(d1) > (double)1.0E-5F || Math.abs(d4) > (double)1.0E-5F) { float f2 = -((float)(Mth.atan2(d1, d4) * (double)(180F / (float)Math.PI))); f2 = Mth.clamp(Mth.wrapDegrees(f2), (float)(-this.maxTurnX), (float)this.maxTurnX); this.mob.setXRot(this.rotlerp(this.mob.getXRot(), f2, 5.0F)); } float f4 = Mth.cos(this.mob.getXRot() * ((float)Math.PI / 180F)); float f3 = Mth.sin(this.mob.getXRot() * ((float)Math.PI / 180F)); this.mob.zza = f4 * f1; this.mob.yya = -f3 * f1; } else { this.mob.setSpeed(f1 * this.outsideWaterSpeedModifier); } } } else { this.mob.setSpeed(0.0F); this.mob.setXxa(0.0F); this.mob.setYya(0.0F); this.mob.setZza(0.0F); } } }
3,130
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SmartAmphibiousMoveControl.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/entity/ai/control/movement/SmartAmphibiousMoveControl.java
package untamedwilds.entity.ai.control.movement; import net.minecraft.util.Mth; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.control.MoveControl; import untamedwilds.entity.ComplexMob; // Copied straight from the vanilla class public class SmartAmphibiousMoveControl extends MoveControl { private final ComplexMob mob; private final int maxTurnX; private final int maxTurnY; private final float inWaterSpeedModifier; private final float outsideWaterSpeedModifier; private final boolean applyGravity; public SmartAmphibiousMoveControl(ComplexMob entityIn, int maxTurnX, int maxTurnY, float waterSpeedFactor, float landSpeedFactor, boolean applyGravity) { super(entityIn); this.mob = entityIn; this.maxTurnX = maxTurnX; this.maxTurnY = maxTurnY; this.inWaterSpeedModifier = waterSpeedFactor; this.outsideWaterSpeedModifier = landSpeedFactor; this.applyGravity = applyGravity; } public void tick() { if (this.mob.canMove()) { if (this.applyGravity && this.mob.isInWater()) { this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(0.0D, 0.005D, 0.0D)); } if (this.operation == Operation.MOVE_TO && !this.mob.getNavigation().isDone()) { double d0 = this.wantedX - this.mob.getX(); double d1 = this.wantedY - this.mob.getY(); double d2 = this.wantedZ - this.mob.getZ(); double d3 = d0 * d0 + d1 * d1 + d2 * d2; if (d3 < (double)2.5000003E-7F) { this.mob.setZza(0.0F); } else { float f = (float)(Mth.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F; this.mob.setYRot(this.rotlerp(this.mob.getYRot(), f, (float)this.maxTurnY)); this.mob.yBodyRot = this.mob.getYRot(); this.mob.yHeadRot = this.mob.getYRot(); float f1 = (float)(this.speedModifier * this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED)); if (this.mob.isInWater()) { this.mob.setSpeed(f1 * this.inWaterSpeedModifier); double d4 = Math.sqrt(d0 * d0 + d2 * d2); if (Math.abs(d1) > (double)1.0E-5F || Math.abs(d4) > (double)1.0E-5F) { float f2 = -((float)(Mth.atan2(d1, d4) * (double)(180F / (float)Math.PI))); f2 = Mth.clamp(Mth.wrapDegrees(f2), (float)(-this.maxTurnX), (float)this.maxTurnX); this.mob.setXRot(this.rotlerp(this.mob.getXRot(), f2, 5.0F)); } float f4 = Mth.cos(this.mob.getXRot() * ((float)Math.PI / 180F)); float f3 = Mth.sin(this.mob.getXRot() * ((float)Math.PI / 180F)); this.mob.zza = f4 * f1; this.mob.yya = -f3 * f1; } else { this.mob.setSpeed(f1 * this.outsideWaterSpeedModifier); } } } else { this.mob.setSpeed(0.0F); this.mob.setXxa(0.0F); this.mob.setYya(0.0F); this.mob.setZza(0.0F); } } } }
3,427
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
UntamedWildsGenerator.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/UntamedWildsGenerator.java
package untamedwilds.world; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.data.worldgen.placement.PlacementUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.CountConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.ProbabilityFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecorator; import net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecoratorType; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.placement.RarityFilter; import net.minecraftforge.event.world.BiomeLoadingEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.gen.feature.*; import java.util.Map; import java.util.function.Supplier; @Mod.EventBusSubscriber(modid = UntamedWilds.MOD_ID) public class UntamedWildsGenerator { public static final DeferredRegister<ConfiguredFeature<?,?>> CONFIGURED_FEATURES = DeferredRegister.create(Registry.CONFIGURED_FEATURE_REGISTRY, UntamedWilds.MOD_ID); public static final DeferredRegister<PlacedFeature> PLACED_FEATURES = DeferredRegister.create(Registry.PLACED_FEATURE_REGISTRY, UntamedWilds.MOD_ID); public static final DeferredRegister<Feature<?>> FEATURES = DeferredRegister.create(ForgeRegistries.FEATURES, UntamedWilds.MOD_ID); public static final DeferredRegister<TreeDecoratorType<?>> TREE_DECORATION = DeferredRegister.create(ForgeRegistries.TREE_DECORATOR_TYPES, UntamedWilds.MOD_ID); public static final Map<String, Float> biodiversity_levels = new java.util.HashMap<>(); private static final RegistryObject<Feature<CountConfiguration>> SEA_ANEMONE = regFeature("sea_anemone", () -> new FeatureSeaAnemone(CountConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> REEDS = regFeature("reeds", () -> new FeatureReedClusters(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> ALGAE = regFeature("algae", () -> new FeatureUnderwaterAlgae(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<ProbabilityFeatureConfiguration>> VEGETATION = regFeature("vegetation", () -> new FeatureVegetation(ProbabilityFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> FLOATING_VEGETATION = regFeature("floating_vegetation", () -> new FeatureFloatingPlants(NoneFeatureConfiguration.CODEC)); // TODO: Unused because can't attach decorators to vanilla features. If I ever implement trees, this will go there public static final RegistryObject<TreeDecoratorType<?>> TREE_ORCHID = TREE_DECORATION.register("orchid", () -> new TreeDecoratorType<>(TreeDecorator.CODEC)); public static final RegistryObject<Feature<NoneFeatureConfiguration>> UNDERGROUND = regFeature("underground", () -> new FeatureUndergroundFaunaLarge(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<ConfiguredFeature<?,?>> UNDERGROUND_CONFIGURED = CONFIGURED_FEATURES.register("underground", () -> new ConfiguredFeature<>(UNDERGROUND.get(), FeatureConfiguration.NONE)); private static final RegistryObject<PlacedFeature> UNDERGROUND_PLACED = PLACED_FEATURES.register("underground", () -> new PlacedFeature(UNDERGROUND_CONFIGURED.getHolder().get(), FeatureUndergroundFaunaLarge.placed())); private static final RegistryObject<Feature<NoneFeatureConfiguration>> APEX = regFeature("apex_predator", () -> new FeatureApexPredators(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> HERBIVORES = regFeature("herbivores", () -> new FeatureHerbivores(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> CRITTERS = regFeature("critter", () -> new FeatureCritters(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> SESSILE = regFeature("sessile", () -> new FeatureOceanSessileSpawns(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> OCEAN = regFeature("ocean_rare", () -> new FeatureOceanSwimming(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> DENSE_WATER = regFeature("dense_water", () -> new FeatureDenseWater(NoneFeatureConfiguration.CODEC)); private static final RegistryObject<Feature<NoneFeatureConfiguration>> CRITTER_BURROW = regFeature("burrow", () -> new FeatureCritterBurrow(NoneFeatureConfiguration.CODEC)); private static <B extends Feature<?>> RegistryObject<B> regFeature(String name, Supplier<? extends B> supplier) { return UntamedWildsGenerator.FEATURES.register(name, supplier); } @SubscribeEvent public static void onBiomesLoad(BiomeLoadingEvent event) { // Thanks Mojang, very cool 😎 // event.getSpawns().withSpawner() //Features.JUNGLE_TREE.getConfig().decorators.add(new TreeOrchidDecorator()); if (event.getCategory() == Biome.BiomeCategory.OCEAN) { registerFeatureWithFreq(event, GenerationStep.Decoration.TOP_LAYER_MODIFICATION, new ConfiguredFeature<>(SESSILE.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqSessile.get()); registerFeatureWithFreq(event, GenerationStep.Decoration.TOP_LAYER_MODIFICATION, new ConfiguredFeature<>(OCEAN.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqOcean.get()); if (!event.getName().toString().equals("minecraft:frozen_ocean") && !event.getName().toString().equals("minecraft:deep_frozen_ocean")) { if (ConfigFeatureControl.addAnemones.get()) { registerFeatureWithFreq(event, GenerationStep.Decoration.VEGETAL_DECORATION, new ConfiguredFeature<>(SEA_ANEMONE.get(), new CountConfiguration(4)), 6); } } } if ((event.getCategory() == Biome.BiomeCategory.JUNGLE)) registerFeatureWithFreq(event, GenerationStep.Decoration.VEGETAL_DECORATION, new ConfiguredFeature<>(FLOATING_VEGETATION.get(), FeatureConfiguration.NONE), 1, ConfigFeatureControl.addAlgae.get()); if ((event.getCategory() == Biome.BiomeCategory.RIVER || event.getCategory() == Biome.BiomeCategory.JUNGLE || event.getCategory() == Biome.BiomeCategory.SWAMP) && !ConfigFeatureControl.reedBlacklist.get().contains(event.getName().toString())) registerFeatureWithFreq(event, GenerationStep.Decoration.VEGETAL_DECORATION, new ConfiguredFeature<>(REEDS.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqReeds.get(), ConfigFeatureControl.addReeds.get()); if (!ConfigFeatureControl.algaeBlacklist.get().contains(event.getName().toString())) registerFeatureWithFreq(event, GenerationStep.Decoration.VEGETAL_DECORATION, new ConfiguredFeature<>(ALGAE.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqAlgae.get(), ConfigFeatureControl.addAlgae.get()); if (!ConfigFeatureControl.floraBlacklist.get().contains(event.getName().toString())) registerFeatureWithFreq(event, GenerationStep.Decoration.VEGETAL_DECORATION, new ConfiguredFeature<>(VEGETATION.get(), new ProbabilityFeatureConfiguration(4)), ConfigFeatureControl.freqFlora.get(), ConfigFeatureControl.addFlora.get()); registerFeatureWithFreq(event, GenerationStep.Decoration.TOP_LAYER_MODIFICATION, new ConfiguredFeature<>(DENSE_WATER.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqWater.get()); registerFeatureWithFreq(event, GenerationStep.Decoration.TOP_LAYER_MODIFICATION, new ConfiguredFeature<>(ConfigFeatureControl.addBurrows.get() ? CRITTER_BURROW.get() : CRITTERS.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqCritter.get()); registerFeatureWithFreq(event, GenerationStep.Decoration.TOP_LAYER_MODIFICATION, new ConfiguredFeature<>(APEX.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqApex.get()); registerFeatureWithFreq(event, GenerationStep.Decoration.TOP_LAYER_MODIFICATION, new ConfiguredFeature<>(HERBIVORES.get(), FeatureConfiguration.NONE), ConfigFeatureControl.freqHerbivores.get()); // TODO: Restore intended Underground fauna generation // TODO: Currently only applies to "Underground" biomes, extend to any biome? if ((event.getCategory() == Biome.BiomeCategory.UNDERGROUND) && ConfigFeatureControl.probUnderground.get() != 0 && /*!FaunaHandler.getSpawnableList(FaunaHandler.animalType.LARGE_UNDERGROUND).isEmpty() &&*/ ConfigMobControl.masterSpawner.get()) { event.getGeneration().addFeature(GenerationStep.Decoration.UNDERGROUND_DECORATION, UNDERGROUND_PLACED.getHolder().get()); } } private static void registerFeatureWithFreq(BiomeLoadingEvent event, GenerationStep.Decoration decoration, ConfiguredFeature<?, ?> feature, int freq) { registerFeatureWithFreq(event, decoration, feature, freq, ConfigMobControl.masterSpawner.get()); } private static void registerFeatureWithFreq(BiomeLoadingEvent event, GenerationStep.Decoration decoration, ConfiguredFeature<?, ?> feature, int freq, boolean enable) { if (freq > 0 && enable) { //Holder.direct(new PlacedFeature(Holder.hackyErase(p_206507_), List.of(p_206508_))) //Holder<PlacedFeature> feature = new Holder<PlacedFeature>(); registerFeature(event, decoration, PlacementUtils.inlinePlaced(Holder.direct(feature), RarityFilter.onAverageOnceEvery(freq)), feature.feature().getRegistryName()); //registerFeature(event, decoration, PlacementUtils.register(feature.feature().getRegistryName().getPath(), Holder.direct(feature), RarityFilter.onAverageOnceEvery(freq)), feature.feature().getRegistryName()); } } private static void registerFeature(BiomeLoadingEvent event, GenerationStep.Decoration decoration, Holder<PlacedFeature> feature, ResourceLocation name) { if (UntamedWilds.DEBUG) UntamedWilds.LOGGER.info("Adding feature " + name + " to biome " + event.getName()); event.getGeneration().addFeature(decoration, feature); } public static void readBioDiversityLevels() { /*try (InputStream inputstream = Language.class.getResourceAsStream("/data/untamedwilds/tags/biodiversity_levels.json")) { JsonObject jsonobject = new Gson().fromJson(new InputStreamReader(inputstream, StandardCharsets.UTF_8), JsonObject.class); for(Map.Entry<String, JsonElement> entry : jsonobject.entrySet()) { biodiversity_levels.put(entry.getKey(), entry.getValue().getAsFloat()); } } catch (JsonParseException | IOException ioexception) { UntamedWilds.LOGGER.error("Couldn't read data from /data/untamedwilds/tags/biodiversity_levels.json", ioexception); }*/ } // Returns the biodiversity level of a biome. Values are data-driven, defaulting to 0.6 if no key is found. public static float getBioDiversityLevel(ResourceLocation biome) { String key = biome.toString(); if (biodiversity_levels.containsKey(key)) { return biodiversity_levels.get(key); } return 0.6F; } }
12,135
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FaunaHandler.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/FaunaHandler.java
package untamedwilds.world; import com.google.common.collect.Lists; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.random.WeightedEntry; import net.minecraft.world.entity.EntityType; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMobTerrestrial; import untamedwilds.util.SpawnDataHolder; import java.util.Collections; import java.util.List; import java.util.Random; public abstract class FaunaHandler { private final static List<SpawnListEntry> spawnCritter = Lists.newArrayList(); private final static List<SpawnListEntry> spawnUndergroundLarge = Lists.newArrayList(); private final static List<SpawnListEntry> spawnLargePrey = Lists.newArrayList(); // This list is meant to populate rivers and water bodies with fish, and has higher density to compensate for the scarcity of water private final static List<SpawnListEntry> spawnDenseWater = Lists.newArrayList(); private final static List<SpawnListEntry> spawnOcean = Lists.newArrayList(); private final static List<SpawnListEntry> spawnSessile = Lists.newArrayList(); private final static List<SpawnListEntry> spawnApexPred = Lists.newArrayList(); public FaunaHandler() { } public static List<SpawnListEntry> getSpawnableList(animalType type) { return switch (type) { case CRITTER -> spawnCritter; case BENTHOS -> spawnSessile; case DENSE_WATER -> spawnDenseWater; case LARGE_OCEAN -> spawnOcean; case LARGE_HERB -> spawnLargePrey; case APEX_PRED -> spawnApexPred; case LARGE_UNDERGROUND -> spawnUndergroundLarge; }; } public static List<SpawnListEntry> getSpawnableList(String type) { switch (type) { case "critter" -> { return spawnCritter; } case "benthos" -> { return spawnSessile; } case "water_river" -> { return spawnDenseWater; } case "water_ocean" -> { return spawnOcean; } case "herbivores" -> { return spawnLargePrey; } case "predators" -> { return spawnApexPred; } case "underground" -> { return spawnUndergroundLarge; } } return null; } public static class SpawnListEntry extends WeightedEntry.IntrusiveBase { public static final Codec<FaunaHandler.SpawnListEntry> CODEC = RecordCodecBuilder.create((p_237051_0_) -> p_237051_0_.group( Codec.STRING.fieldOf("type").orElse("").forGetter((p_237056_0_) -> p_237056_0_.entityName), Codec.INT.fieldOf("weight").orElse(0).forGetter((p_237054_0_) -> p_237054_0_.itemWeight), Codec.INT.fieldOf("size_min").orElse(0).forGetter((p_237055_0_) -> p_237055_0_.minGroupCount), Codec.INT.fieldOf("size_max").orElse(0).forGetter((p_237054_0_) -> p_237054_0_.maxGroupCount)) .apply(p_237051_0_, FaunaHandler.SpawnListEntry::new)); public String entityName; public EntityType<?> entityType; public int itemWeight; public int minGroupCount; public int maxGroupCount; public SpawnListEntry(String entityName, Integer weight, Integer minGroupCount, Integer maxGroupCount) { super(weight); this.entityType = ForgeRegistries.ENTITIES.getValue(new ResourceLocation(entityName)); this.itemWeight = weight; this.minGroupCount = minGroupCount; this.maxGroupCount = maxGroupCount; } public SpawnListEntry(EntityType<?> entityTypeIn, int weight, int minGroupCount, int maxGroupCount) { super(weight); this.entityType = entityTypeIn; this.itemWeight = weight; this.minGroupCount = minGroupCount; this.maxGroupCount = maxGroupCount; } public String toString() { return EntityType.getKey(this.entityType) + "*(" + this.minGroupCount + "-" + this.maxGroupCount + "):" + this.itemWeight; } public Integer getGroupCount() { if (this.minGroupCount >= this.maxGroupCount) return this.minGroupCount; return new Random().nextInt(this.minGroupCount, this.maxGroupCount); } } public enum animalType { CRITTER ("critter"), BENTHOS("benthos"), DENSE_WATER ("water_river"), LARGE_OCEAN ("water_ocean"), LARGE_HERB ("herbivores"), LARGE_UNDERGROUND ("underground"), APEX_PRED ("predators"); public String name; animalType(String name) { this.name = name; } } }
5,018
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FaunaSpawn.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/FaunaSpawn.java
package untamedwilds.world; import net.minecraft.core.BlockPos; import net.minecraft.tags.BlockTags; import net.minecraft.tags.FluidTags; import net.minecraft.util.Mth; import net.minecraft.world.entity.*; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.material.FluidState; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigMobControl; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.entity.ISpecies; import untamedwilds.util.EntityUtils; import javax.annotation.Nullable; import java.util.Objects; import java.util.Random; public class FaunaSpawn { private static boolean isSpawnableSpace(BlockGetter worldIn, BlockPos pos, BlockState state, FluidState fluidStateIn, EntityType<?> entityTypeIn) { if (state.isCollisionShapeFullBlock(worldIn, pos)) { return false; } else if (state.isSignalSource()) { return false; } else if (!fluidStateIn.isEmpty()) { return false; } else if (state.is(BlockTags.PREVENT_MOB_SPAWNING_INSIDE)) { return false; } else { return !entityTypeIn.isBlockDangerous(state); } } private static boolean canCreatureTypeSpawnAtLocation(SpawnPlacements.Type placeType, LevelReader worldIn, BlockPos pos, @Nullable EntityType<?> entityTypeIn) { if (placeType == SpawnPlacements.Type.NO_RESTRICTIONS) { return true; } else if (entityTypeIn != null && worldIn.getWorldBorder().isWithinBounds(pos)) { return canSpawnAtBody(placeType, worldIn, pos, entityTypeIn); } return false; } private static boolean canSpawnAtBody(SpawnPlacements.Type placeType, LevelReader worldIn, BlockPos pos, @Nullable EntityType<?> entityTypeIn) { BlockState blockstate = worldIn.getBlockState(pos); FluidState ifluidstate = worldIn.getFluidState(pos); //BlockPos blockpos = pos.up(); BlockPos blockpos1 = pos.below(); switch(placeType) { case IN_WATER: return ifluidstate.is(FluidTags.WATER) /*&& worldIn.getFluidState(blockpos1).isTagged(FluidTags.WATER) && !worldIn.getBlockState(blockpos).isNormalCube(worldIn, blockpos)*/; case IN_LAVA: return ifluidstate.is(FluidTags.LAVA); case ON_GROUND: default: BlockState blockstate1 = worldIn.getBlockState(blockpos1); if (!blockstate1.isValidSpawn(worldIn, blockpos1, placeType, entityTypeIn)) { return false; } else { return isSpawnableSpace(worldIn, pos, blockstate, ifluidstate, entityTypeIn); /* && isSpawnableSpace(worldIn, blockpos, worldIn.getBlockState(blockpos), worldIn.getFluidState(blockpos)*/ } } } //public static boolean performWorldGenSpawning(EntityType<?> entityType, EntitySpawnPlacementRegistry.PlacementType spawnType, ISeedReader worldIn, BlockPos pos, Random rand, int groupSize) { // return performWorldGenSpawning(entityType, spawnType, Heightmap.Type.WORLD_SURFACE, worldIn, pos, rand, groupSize); //} public static boolean performWorldGenSpawning(EntityType<?> entityType, SpawnPlacements.Type spawnType, @Nullable Heightmap.Types heightMap, ServerLevelAccessor worldIn, BlockPos pos, Random random, int groupSize) { //UntamedWilds.LOGGER.info(entityType); if (ConfigMobControl.dimensionBlacklist.get().contains(worldIn.getLevel().dimension().location().toString())) return false; if (entityType != null && !worldIn.isClientSide()) { int i = pos.getX() + random.nextInt(16); int j = pos.getZ() + random.nextInt(16); if (heightMap != null) { pos.offset(i, 0, j); pos = worldIn.getHeightmapPos(heightMap, pos); //worldIn.setBlockState(pos, Blocks.TORCH.defaultBlockState(), 2); } if (random.nextFloat() < UntamedWildsGenerator.getBioDiversityLevel(Objects.requireNonNull(worldIn.getBiome(pos).value().getRegistryName()))) { int k = 1; // This variable will be changed after the mob spawns int species = -1; for(int packSize = 0; packSize < k; ++packSize) { int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); if (packSize != 0) { // Do not offset the first entity of the pack x += random.nextInt(6); z += random.nextInt(6); } for(int attempt = 0; attempt < 4; ++attempt) { // 4 attempts at spawning are made for each mob if (attempt != 0) { if (attempt == 1) { y += ConfigMobControl.treeSpawnBias.get(); } x += random.nextInt(2); z += random.nextInt(2); } BlockPos blockpos = new BlockPos(x, y, z); //BlockPos blockpos = getTopSolidOrLiquidBlock(worldIn, entityType, x, z); if (entityType.canSummon() && canCreatureTypeSpawnAtLocation(spawnType, worldIn, blockpos, entityType)) { float f = entityType.getWidth(); double d0 = Mth.clamp(x, (double)blockpos.getX() + (double)f, (double)blockpos.getX() + 16.0D - (double)f); double d1 = Mth.clamp(z, (double)blockpos.getZ() + (double)f, (double)blockpos.getZ() + 16.0D - (double)f); if (!worldIn.noCollision(entityType.getAABB(d0, y, d1)) || !SpawnPlacements.checkSpawnRules(entityType, worldIn, MobSpawnType.CHUNK_GENERATION, blockpos, worldIn.getRandom())) { continue; } Entity entity; try { entity = entityType.create(worldIn.getLevel()); } catch (Exception exception) { UntamedWilds.LOGGER.warn("Failed to create mob", exception); continue; } assert entity != null; entity.moveTo(blockpos.getX(), blockpos.getY(), blockpos.getZ(), random.nextFloat() * 360.0F, 0.0F); if (entity instanceof Mob mobEntity) { if (net.minecraftforge.common.ForgeHooks.canEntitySpawn(mobEntity, worldIn, d0, blockpos.getY(), d1, null, MobSpawnType.CHUNK_GENERATION) == -1) continue; if (mobEntity.checkSpawnRules(worldIn, MobSpawnType.CHUNK_GENERATION) && worldIn.noCollision(entity)) { mobEntity.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(mobEntity.blockPosition()), MobSpawnType.CHUNK_GENERATION, null, null); if (mobEntity instanceof ComplexMob && mobEntity.isAlive()) { if (mobEntity instanceof ISpecies) { if (species == -1) { species = ((ComplexMob)mobEntity).getVariant(); if (species != 99) k = EntityUtils.getPackSize(entityType, species); } else { ((ComplexMob)mobEntity).setVariant(species); ((ComplexMob)mobEntity).chooseSkinForSpecies((ComplexMob)mobEntity, false); if (mobEntity instanceof INeedsPostUpdate) { ((INeedsPostUpdate)mobEntity).updateAttributes(); } } // Wrong spawning messages are most likely due to their inclusion on onMobSpawning, not here } // Two possible fail-states, entity being assigned variant 99 (no valid variant found) or the Entity Data does not exist if (((ComplexMob)mobEntity).getVariant() == 99 || !ComplexMob.ENTITY_DATA_HASH.containsKey(entityType)) { mobEntity.remove(Entity.RemovalReason.DISCARDED); return false; } } if (UntamedWilds.DEBUG && mobEntity instanceof ComplexMob && mobEntity.isAlive()) { if (mobEntity instanceof ISpecies) UntamedWilds.LOGGER.info("Spawned: " + ((ComplexMob)mobEntity).getGenderString() + " " + ((ISpecies)mobEntity).getSpeciesName()); else UntamedWilds.LOGGER.info("Spawned: " + ((ComplexMob)mobEntity).getGenderString() + " " + mobEntity.getName().getString()); } if (mobEntity.isAlive()) { worldIn.addFreshEntityWithPassengers(mobEntity); } break; } } } } } return true; } } return false; } /*private static BlockPos getTopSolidOrLiquidBlock(LevelReader worldIn, @Nullable EntityType<?> entity, int posX, int posZ) { BlockPos blockpos = new BlockPos(posX, worldIn.getBbHeight(EntitySpawnPlacementRegistry.func_209342_b(entity), posX, posZ), posZ); BlockPos blockpos1 = blockpos.below(); return worldIn.getBlockState(blockpos1).allowsMovement(worldIn, blockpos1, PathType.WATER) ? blockpos1 : blockpos; }*/ }
10,664
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureReedClusters.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureReedClusters.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.Direction; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.GrassBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.Blocks; import net.minecraft.core.BlockPos; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.block.ReedBlock; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.init.ModBlock; import untamedwilds.init.ModTags.ModBlockTags; import java.util.Random; public class FeatureReedClusters extends Feature<NoneFeatureConfiguration> { public FeatureReedClusters(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { boolean flag = false; Random rand = context.level().getRandom(); WorldGenLevel world = context.level(); if (ConfigFeatureControl.dimensionFeatureBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; BlockPos pos = world.getHeightmapPos(Heightmap.Types.OCEAN_FLOOR, context.origin()); int attempts = world.getBiome(pos).value().biomeCategory == Biome.BiomeCategory.RIVER ? 3 : 1; for(int k = 0; k < attempts; ++k) { pos = pos.offset(rand.nextInt(8) - rand.nextInt(8), 0, rand.nextInt(8) - rand.nextInt(8)); for(int i = 0; i < 16; ++i) { BlockPos blockpos = pos.offset(rand.nextInt(8) - rand.nextInt(8), rand.nextInt(3) - rand.nextInt(3), rand.nextInt(8) - rand.nextInt(8)); Biome biome = world.getBiome(pos).value(); if(world.getFluidState(blockpos.above(3)).isEmpty() && world.getBlockState(blockpos.below()).is(ModBlockTags.REEDS_PLANTABLE_ON) && (biome.biomeCategory == Biome.BiomeCategory.RIVER || biome.biomeCategory == Biome.BiomeCategory.JUNGLE || biome.biomeCategory == Biome.BiomeCategory.SWAMP)) { if(!world.getBlockState(blockpos).isFaceSturdy(context.level(), blockpos, Direction.UP) || (world.getBlockState(blockpos).getBlock() == Blocks.WATER && world.isEmptyBlock(blockpos.above()))) { int height = rand.nextInt(4); for (int j = 0; j <= height; ++j) { if (world.getBlockState(pos).getBlock() == Blocks.SNOW && world.getBlockState(pos.below()).getBlock() == Blocks.GRASS_BLOCK) world.setBlock(pos.below(), Blocks.GRASS_BLOCK.defaultBlockState().setValue(GrassBlock.SNOWY, false), 2); // TODO: Shitty hack to fix grey grass in snowy biomes int fluidstate = world.getFluidState(blockpos.above(j)).isEmpty() ? 1 : 2; BlockState blockstate = ((ReedBlock) ModBlock.COMMON_REED.get()).getStateForWorldgen(world, blockpos.above(j)); if (blockstate != null) { world.setBlock(blockpos.above(j), blockstate.setValue(ReedBlock.PROPERTY_AGE, j == height ? 0 : fluidstate), 2); } } flag = true; } } } } return flag; } }
3,593
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureCritterBurrow.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureCritterBurrow.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.*; import net.minecraft.resources.ResourceKey; import net.minecraft.util.random.WeightedRandom; import net.minecraft.core.BlockPos; import net.minecraft.world.level.LevelSimulatedReader; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.GrassBlock; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.material.Material; import untamedwilds.block.CritterBurrowBlock; import untamedwilds.block.blockentity.CritterBurrowBlockEntity; import untamedwilds.config.ConfigMobControl; import untamedwilds.entity.ComplexMobAmphibious; import untamedwilds.entity.ISpecies; import untamedwilds.init.ModBlock; import untamedwilds.world.FaunaHandler; import java.util.Optional; import java.util.Random; public class FeatureCritterBurrow extends Feature<NoneFeatureConfiguration> { public FeatureCritterBurrow(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; int i = rand.nextInt(8) - rand.nextInt(8); int j = rand.nextInt(8) - rand.nextInt(8); int k = world.getHeight(Heightmap.Types.OCEAN_FLOOR_WG, pos.getX() + i, pos.getZ() + j); pos = new BlockPos(pos.getX() + i, k, pos.getZ() + j); Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.CRITTER)); if (entry.isPresent()) { Entity entity = entry.get().entityType.create(world.getLevel()); int variant = -1; if (entity != null && isReplaceablePlant(world, pos)) { if (!world.getFluidState(pos).isEmpty() && !(entity instanceof ComplexMobAmphibious)) return false; if (entity instanceof ISpecies) { variant = ((ISpecies) entity).setSpeciesByBiome(world.getBiome(pos), MobSpawnType.CHUNK_GENERATION); if (variant == 99) { entity.discard(); return false; } } if (world.getBlockState(pos).getBlock() == Blocks.SNOW && world.getBlockState(pos.below()).getBlock() == Blocks.GRASS_BLOCK) world.setBlock(pos.below(), Blocks.GRASS_BLOCK.defaultBlockState().setValue(GrassBlock.SNOWY, false), 2); // TODO: Shitty hack to fix grey grass in snowy biomes if (world.getBlockEntity(pos) == null) { world.setBlock(pos, ModBlock.BURROW.get().defaultBlockState().setValue(CritterBurrowBlock.WATERLOGGED, !world.getFluidState(pos).isEmpty()), 2); if (world.getBlockState(pos).getBlock() == ModBlock.BURROW.get()) { CritterBurrowBlockEntity te = (CritterBurrowBlockEntity) world.getBlockEntity(pos); if (te != null) { te.setCount(Math.max(4, entry.get().getGroupCount() * (rand.nextInt(3) + 1))); te.setEntityType(entry.get().entityType); if (variant >= 0) te.setVariant(variant); } entity.discard(); return true; } } } } return false; } private static boolean isReplaceablePlant(LevelSimulatedReader p_67289_, BlockPos p_67290_) { return p_67289_.isStateAtPosition(p_67290_, (p_160551_) -> { Material material = p_160551_.getMaterial(); return material == Material.REPLACEABLE_PLANT || material == Material.AIR; }); } }
4,432
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureSeaAnemone.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureSeaAnemone.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.SeaPickleBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.CountConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.ProbabilityFeatureConfiguration; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.init.ModBlock; import java.util.Random; public class FeatureSeaAnemone extends Feature<CountConfiguration> { public FeatureSeaAnemone(Codec<CountConfiguration> p_i231987_1_) { super(p_i231987_1_); } public boolean place(FeaturePlaceContext<CountConfiguration> context) { Random rand = context.level().getRandom(); WorldGenLevel world = context.level(); BlockPos pos = world.getHeightmapPos(Heightmap.Types.OCEAN_FLOOR, context.origin()); if (ConfigFeatureControl.dimensionFeatureBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; if (pos.getY() > 44 && pos.getY() < 62) { int i = 0; int m = rand.nextInt(3); Block type = switch (m) { case 1 -> ModBlock.ANEMONE_SAND.get(); case 2 -> ModBlock.ANEMONE_SEBAE.get(); default -> ModBlock.ANEMONE_ROSE_BULB.get(); }; for(int j = 0; j < context.config().count().sample(rand); ++j) { int k = rand.nextInt(8) - rand.nextInt(8); int l = rand.nextInt(8) - rand.nextInt(8); int i1 = world.getHeight(Heightmap.Types.OCEAN_FLOOR, pos.getX() + k, pos.getZ() + l); BlockPos blockpos = new BlockPos(pos.getX() + k, i1, pos.getZ() + l); BlockState blockstate = type.defaultBlockState(); if (i1 < 62 && world.getBlockState(blockpos).is(Blocks.WATER) && blockstate.canSurvive(world, blockpos)) { world.setBlock(blockpos, blockstate, 2); ++i; } } return i > 0; } return false; } }
2,661
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureCritters.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureCritters.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.util.random.WeightedRandom; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Optional; import java.util.Random; public class FeatureCritters extends Feature<NoneFeatureConfiguration> { public FeatureCritters(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for (int i = 0; i < 5; i++) { Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.CRITTER)); if (entry.isPresent()) { EntityType<?> type = entry.get().entityType; if (FaunaSpawn.performWorldGenSpawning(type, SpawnPlacements.Type.NO_RESTRICTIONS, Heightmap.Types.WORLD_SURFACE_WG, world, pos, rand, entry.get().getGroupCount())) { return true; } } } return false; } }
1,852
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureApexPredators.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureApexPredators.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.util.random.WeightedRandom; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.level.Level; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Optional; import java.util.Random; public class FeatureApexPredators extends Feature<NoneFeatureConfiguration> { public FeatureApexPredators(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for (int i = 0; i < 3; i++) { Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.APEX_PRED)); if (entry.isPresent()) { EntityType<?> type = entry.get().entityType; if (type != null) { if (FaunaSpawn.performWorldGenSpawning(type, SpawnPlacements.Type.NO_RESTRICTIONS, Heightmap.Types.WORLD_SURFACE_WG, world, pos, rand, entry.get().getGroupCount())) { return true; } } } } return false; } }
2,219
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureOceanSwimming.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureOceanSwimming.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.util.random.WeightedRandom; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Optional; import java.util.Random; public class FeatureOceanSwimming extends Feature<NoneFeatureConfiguration> { public FeatureOceanSwimming(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for (int i = 0; i < 5; i++) { Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.LARGE_OCEAN)); if (entry.isPresent()) { if (FaunaSpawn.performWorldGenSpawning(entry.get().entityType, SpawnPlacements.Type.IN_WATER, Heightmap.Types.OCEAN_FLOOR, world, pos, rand, entry.get().getGroupCount())) { return true; } } } return false; } }
1,765
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureFloatingPlants.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureFloatingPlants.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.material.Fluids; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.config.ConfigMobControl; import untamedwilds.init.ModBlock; import java.util.Random; public class FeatureFloatingPlants extends Feature<NoneFeatureConfiguration> { public FeatureFloatingPlants(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { boolean flag = false; Random rand = context.level().getRandom(); WorldGenLevel world = context.level(); BlockPos pos = world.getHeightmapPos(Heightmap.Types.OCEAN_FLOOR, context.origin()); if (ConfigFeatureControl.dimensionFeatureBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for(int i = 0; i < 64; ++i) { BlockPos blockpos = pos.offset(rand.nextInt(6) - rand.nextInt(6), rand.nextInt(2) - rand.nextInt(2), rand.nextInt(6) - rand.nextInt(6)); if(world.getFluidState(blockpos.below()).getType() == Fluids.WATER && world.isEmptyBlock(blockpos)) { world.setBlock(blockpos, ModBlock.WATER_HYACINTH.get().defaultBlockState(), 2); flag = true; } } return flag; } }
1,738
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureDenseWater.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureDenseWater.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.util.random.WeightedRandom; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Optional; import java.util.Random; public class FeatureDenseWater extends Feature<NoneFeatureConfiguration> { public FeatureDenseWater(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for (int i = 0; i < 5; i++) { Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.DENSE_WATER)); if (entry.isPresent()) { if (FaunaSpawn.performWorldGenSpawning(entry.get().entityType, SpawnPlacements.Type.IN_WATER, Heightmap.Types.OCEAN_FLOOR, world, pos, rand, entry.get().getGroupCount())) { return true; } } } return false; } }
1,759
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureHerbivores.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureHerbivores.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.util.random.WeightedRandom; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Optional; import java.util.Random; public class FeatureHerbivores extends Feature<NoneFeatureConfiguration> { public FeatureHerbivores(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for (int i = 0; i < 3; i++) { Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.LARGE_HERB)); if (entry.isPresent()) { EntityType<?> type = entry.get().entityType; if (FaunaSpawn.performWorldGenSpawning(type, SpawnPlacements.Type.NO_RESTRICTIONS, Heightmap.Types.WORLD_SURFACE_WG, world, pos, rand, entry.get().getGroupCount())) { return true; } } } return false; } }
1,893
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureOceanSessileSpawns.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureOceanSessileSpawns.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.util.random.WeightedRandom; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Optional; import java.util.Random; public class FeatureOceanSessileSpawns extends Feature<NoneFeatureConfiguration> { public FeatureOceanSessileSpawns(Codec<NoneFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for (int i = 0; i < 5; i++) { Optional<FaunaHandler.SpawnListEntry> entry = WeightedRandom.getRandomItem(rand, FaunaHandler.getSpawnableList(FaunaHandler.animalType.BENTHOS)); if (entry.isPresent()) { if (FaunaSpawn.performWorldGenSpawning(entry.get().entityType, SpawnPlacements.Type.NO_RESTRICTIONS, Heightmap.Types.OCEAN_FLOOR, world, pos, rand, entry.get().getGroupCount())) { return true; } } } return false; } }
1,812
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureVegetation.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureVegetation.java
package untamedwilds.world.gen.feature; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.GrassBlock; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.ProbabilityFeatureConfiguration; import untamedwilds.block.IPostGenUpdate; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.init.ModBlock; import untamedwilds.init.ModTags.ModBlockTags; import java.util.ArrayList; import java.util.List; import java.util.Random; public class FeatureVegetation extends Feature<ProbabilityFeatureConfiguration> { public FeatureVegetation(Codec<ProbabilityFeatureConfiguration> codec) { super(codec); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); WorldGenLevel world = context.level(); BlockPos genPos = world.getHeightmapPos(Heightmap.Types.OCEAN_FLOOR, context.origin()); if (ConfigFeatureControl.dimensionFeatureBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; boolean flag = false; int x = rand.nextInt(16) - 8; int z = rand.nextInt(16) - 8; BlockPos pos = genPos.offset(x, 0, z); Pair<Block, Integer> flora = FloraTypes.getFloraForPos(world, genPos); if (flora != null) { Block block = flora.getFirst(); int size = flora.getSecond(); for(int i = 0; i < size; ++i) { BlockPos blockpos = pos.offset(rand.nextInt(6) - rand.nextInt(6), rand.nextInt(2) - rand.nextInt(2), rand.nextInt(6) - rand.nextInt(6)); if(world.getBlockState(blockpos.below()).is(ModBlockTags.ALOE_PLANTABLE_ON)) { if (!world.getBlockState(blockpos).isFaceSturdy(world, blockpos, Direction.UP) && (world.getFluidState(blockpos).isEmpty())) { if (block != null) { if (world.getBlockState(blockpos).getBlock() == Blocks.SNOW && world.getBlockState(blockpos.below()).getBlock() == Blocks.GRASS_BLOCK) world.setBlock(blockpos.below(), Blocks.GRASS_BLOCK.defaultBlockState().setValue(GrassBlock.SNOWY, false), 2); // TODO: Shitty hack to fix grey grass in snowy biomes world.setBlock(blockpos, block.defaultBlockState(), 2); if (block instanceof IPostGenUpdate) { ((IPostGenUpdate)block).updatePostGen(world, blockpos); } flag = true; } } } } } return flag; } // Plants available, referenced to properly distribute them in the world if their conditions are filled public enum FloraTypes { TEMPERATE_BUSH (ModBlock.BUSH_TEMPERATE.get(), 6, ConfigFeatureControl.addFlora.get(), false, 24, Biome.BiomeCategory.FOREST, Biome.BiomeCategory.SWAMP, Biome.BiomeCategory.EXTREME_HILLS, Biome.BiomeCategory.TAIGA, Biome.BiomeCategory.PLAINS), CREOSOTE_BUSH (ModBlock.BUSH_CREOSOTE.get(), 2, ConfigFeatureControl.addFlora.get(), false, 4, Biome.BiomeCategory.MESA, Biome.BiomeCategory.DESERT), ELEPHANT_EAR (ModBlock.ELEPHANT_EAR.get(), 6, ConfigFeatureControl.addFlora.get(), false, 24, Biome.BiomeCategory.JUNGLE), HEMLOCK (ModBlock.HEMLOCK.get(), 1, ConfigFeatureControl.addFlora.get(), false, 12, Biome.BiomeCategory.FOREST), TITAN_ARUM (ModBlock.TITAN_ARUM.get(), 6, ConfigFeatureControl.addFlora.get(), false, 1, Biome.BiomeCategory.JUNGLE), ZIMBABWE_ALOE (ModBlock.ZIMBABWE_ALOE.get(), 4, ConfigFeatureControl.addFlora.get(), false, 1, Biome.BiomeCategory.MESA), FLOWER_YARROW (ModBlock.YARROW.get(), 6, ConfigFeatureControl.addFlora.get(), false, 18, Biome.BiomeCategory.FOREST, Biome.BiomeCategory.PLAINS, Biome.BiomeCategory.MOUNTAIN), GRASS_JUNEGRASS (ModBlock.JUNEGRASS.get(), 8, ConfigFeatureControl.addFlora.get(), false, 18, Biome.BiomeCategory.PLAINS), CANOLA (ModBlock.CANOLA.get(), 6, ConfigFeatureControl.addFlora.get(), false, 12, Biome.BiomeCategory.PLAINS); public Block type; public int rarity; public boolean enabled; public boolean spawnsInWater; public int size; public Biome.BiomeCategory[] spawnBiomes; FloraTypes(Block type, int rolls, boolean add, boolean spawnsInWater, int size, Biome.BiomeCategory... biomes) { this.type = type; this.rarity = rolls; this.enabled = add; this.spawnsInWater = spawnsInWater; this.spawnBiomes = biomes; this.size = size; } public static Pair<Block, Integer> getFloraForPos(WorldGenLevel world, BlockPos pos) { Biome biome = world.getBiome(pos).value(); List<FeatureVegetation.FloraTypes> types = new ArrayList<>(); for (FeatureVegetation.FloraTypes type : values()) { if (type.enabled && !(!type.spawnsInWater && world.getBlockState(pos).getBlock() == Blocks.WATER)) { for(Biome.BiomeCategory biomeTypes : type.spawnBiomes) { if(biome.biomeCategory == biomeTypes){ for (int i=0; i < type.rarity; i++) { types.add(type); } } } } } if (!types.isEmpty()) { int i = new Random().nextInt(types.size()); return new Pair<>(types.get(i).type, types.get(i).size); } return null; } } }
6,233
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureUnderwaterAlgae.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureUnderwaterAlgae.java
package untamedwilds.world.gen.feature; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.init.ModBlock; import java.util.*; public class FeatureUnderwaterAlgae extends Feature<NoneFeatureConfiguration> { public FeatureUnderwaterAlgae(Codec<NoneFeatureConfiguration> p_i231988_1_) { super(p_i231988_1_); } public boolean place(FeaturePlaceContext context) { Random rand = context.level().getRandom(); BlockPos pos = context.origin(); WorldGenLevel world = context.level(); if (ConfigFeatureControl.dimensionFeatureBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; boolean flag = false; int i = rand.nextInt(8) - rand.nextInt(8); int j = rand.nextInt(8) - rand.nextInt(8); int k = world.getHeight(Heightmap.Types.OCEAN_FLOOR, pos.getX() + i, pos.getZ() + j); BlockPos blockpos = new BlockPos(pos.getX() + i, k, pos.getZ() + j); Pair<Block, Integer> algae = AlgaeTypes.getAlgaeForPos(world, blockpos); if (world.getBlockState(blockpos).is(Blocks.WATER) && algae != null) { BlockState blockstate = algae.getFirst().defaultBlockState(); if (blockstate.canSurvive(world, blockpos)) { world.setBlock(blockpos, blockstate, 2); flag = true; } } return flag; } // Algae available, referenced to properly distribute them in the world if their conditions are filled public enum AlgaeTypes { AMAZON_SWORD (ModBlock.AMAZON_SWORD.get(), 4, ConfigFeatureControl.addAlgae.get(), 6, Biome.BiomeCategory.SWAMP, Biome.BiomeCategory.JUNGLE), EELGRASS (ModBlock.EELGRASS.get(), 4, ConfigFeatureControl.addAlgae.get(), 6, Biome.BiomeCategory.OCEAN); public Block type; public int rarity; public boolean enabled; public int size; public Biome.BiomeCategory[] spawnBiomes; AlgaeTypes(Block type, int rolls, boolean add, int size, Biome.BiomeCategory... biomes) { this.type = type; this.rarity = rolls; this.enabled = add; this.spawnBiomes = biomes; this.size = size; } public static Pair<Block, Integer> getAlgaeForPos(WorldGenLevel world, BlockPos pos) { Optional<ResourceKey<Biome>> optional = world.getBiome(pos).unwrapKey(); if (Objects.equals(optional, Biomes.FROZEN_OCEAN) || Objects.equals(optional, Optional.of(Biomes.DEEP_FROZEN_OCEAN))) { return null; } Biome biome = world.getBiome(pos).value(); List<AlgaeTypes> types = new ArrayList<>(); for (AlgaeTypes type : values()) { if (type.enabled) { for(Biome.BiomeCategory biomeTypes : type.spawnBiomes) { if(biome.biomeCategory == biomeTypes){ for (int i=0; i < type.rarity; i++) { types.add(type); } } } } } if (!types.isEmpty()) { int i = new Random().nextInt(types.size()); return new Pair<>(types.get(i).type, types.get(i).size); } return null; } } }
3,944
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FeatureUndergroundFaunaLarge.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/feature/FeatureUndergroundFaunaLarge.java
package untamedwilds.world.gen.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.data.worldgen.placement.PlacementUtils; import net.minecraft.util.random.WeightedRandom; import net.minecraft.util.valueproviders.ConstantInt; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.placement.*; import untamedwilds.config.ConfigFeatureControl; import untamedwilds.config.ConfigMobControl; import untamedwilds.world.FaunaHandler; import untamedwilds.world.FaunaSpawn; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Random; public class FeatureUndergroundFaunaLarge extends Feature<NoneFeatureConfiguration> { public FeatureUndergroundFaunaLarge(Codec<NoneFeatureConfiguration> codec) { super(codec); } public static List<PlacementModifier> placed() { return Arrays.asList(CountPlacement.of(1), InSquarePlacement.spread(), PlacementUtils.RANGE_BOTTOM_TO_MAX_TERRAIN_HEIGHT, RandomOffsetPlacement.vertical(ConstantInt.of(ConfigFeatureControl.probUnderground.get())), BiomeFilter.biome()); } @Override public boolean place(FeaturePlaceContext<NoneFeatureConfiguration> config) { WorldGenLevel world = config.level(); BlockPos blockpos = config.origin(); Random rng = config.random(); Optional<FaunaHandler.SpawnListEntry> entry = Optional.empty(); BlockPos.MutableBlockPos setPos = new BlockPos.MutableBlockPos(blockpos.getX(), blockpos.getY(), blockpos.getZ()); final int horiz = 2; final int vert = 2; if (ConfigMobControl.dimensionBlacklist.get().contains(world.getLevel().dimension().location().toString())) return false; for(int i = -horiz; i < horiz + 1; i++) for(int j = -horiz; j < horiz + 1; j++) for(int k = -vert; k < vert + 1; k++) { setPos.set(blockpos.getX() + i, blockpos.getY() + k, blockpos.getZ() + j); if (world.isStateAtPosition(setPos, BlockState::isAir)) { for (int l = 0; l < 5; l++) { if (entry.isEmpty()) entry = WeightedRandom.getRandomItem(rng, FaunaHandler.getSpawnableList(FaunaHandler.animalType.LARGE_UNDERGROUND)); if (entry.isPresent()) { EntityType<?> type = entry.get().entityType; if (type != null) { if (FaunaSpawn.performWorldGenSpawning(type, SpawnPlacements.Type.NO_RESTRICTIONS, null, world, blockpos, rng, entry.get().getGroupCount())) { return true; } } } } } } return true; } }
3,396
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
TreeOrchidDecorator.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/world/gen/treedecorator/TreeOrchidDecorator.java
package untamedwilds.world.gen.treedecorator; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.LevelSimulatedReader; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecorator; import net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecoratorType; import untamedwilds.block.EpyphitePlantBlock; import untamedwilds.init.ModBlock; import untamedwilds.world.UntamedWildsGenerator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.function.BiConsumer; public class TreeOrchidDecorator extends TreeDecorator { public static final Codec<TreeOrchidDecorator> CODEC; public static final TreeOrchidDecorator field_236871_b_ = new TreeOrchidDecorator(); protected TreeDecoratorType<?> func_230380_a_() { return UntamedWildsGenerator.TREE_ORCHID.get(); } static { CODEC = Codec.unit(() -> field_236871_b_); } public void type(LevelSimulatedReader worldIn, BiConsumer<BlockPos, BlockState> p_161746_, Random rand, List<BlockPos> posList, List<BlockPos> blockPosSet) { if (!(rand.nextFloat() >= 0.95)) { int i = posList.get(0).getY(); posList.stream().filter((p_236867_1_) -> { return p_236867_1_.getY() - i <= 2; }).forEach((p_242865_5_) -> { for(Direction direction : Direction.Plane.HORIZONTAL) { if (rand.nextFloat() <= 0.25F) { Direction direction1 = direction.getOpposite(); BlockPos blockpos = p_242865_5_.offset(direction1.getStepX(), 0, direction1.getStepZ()); if (Feature.isAir(worldIn, blockpos)) { BlockState blockstate = ModBlock.ORCHID_RED.get().defaultBlockState().setValue(EpyphitePlantBlock.FACING, direction); this.type(worldIn, p_161746_, rand, posList, blockPosSet); } } } }); } } @Override protected TreeDecoratorType<?> type() { return null; } @Override public void place(LevelSimulatedReader p_161745_, BiConsumer<BlockPos, BlockState> p_161746_, Random p_161747_, List<BlockPos> p_161748_, List<BlockPos> p_161749_) { } }
2,431
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
MobSpawnItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/MobSpawnItem.java
package untamedwilds.item; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.util.EntityUtils; import untamedwilds.util.ModCreativeModeTab; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.function.Supplier; public class MobSpawnItem extends Item { private final Supplier<? extends EntityType<?>> entity; public MobSpawnItem(Supplier<? extends EntityType<?>> typeIn, Properties properties) { super(properties); this.entity = typeIn; } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { EntityUtils.buildTooltipData(stack, tooltip, this.entity.get(), EntityUtils.getVariantName(this.entity.get(), this.getSpecies(stack))); } public Component getName(ItemStack stack) { return new TranslatableComponent("entity.untamedwilds." + this.entity.get().getRegistryName().getPath() + "_" + EntityUtils.getVariantName(this.entity.get(), this.getSpecies(stack))); //return new TranslatableComponent("entity.untamedwilds." + this.entity.getRegistryName().getPath() + "_" + ComplexMob.getEntityData(this.entity).getSpeciesData().get(this.getSpecies(stack)).getName()).getString(); } @Override public InteractionResult useOn(UseOnContext useContext) { Level worldIn = useContext.getLevel(); if (!(worldIn instanceof ServerLevel)) { return InteractionResult.SUCCESS; } else { ItemStack itemStack = useContext.getItemInHand(); BlockPos pos = useContext.getClickedPos(); Direction facing = useContext.getClickedFace(); BlockState blockState = worldIn.getBlockState(pos); BlockPos spawnPos = blockState.getCollisionShape(worldIn, pos).isEmpty() ? pos : pos.relative(facing); EntityType<?> entity = EntityUtils.getEntityTypeFromTag(itemStack.getTag(), this.entity.get()); boolean doVerticalOffset = !Objects.equals(pos, spawnPos) && facing == Direction.UP; EntityUtils.createMobFromItem((ServerLevel) worldIn, itemStack, entity, this.getSpecies(itemStack), spawnPos, useContext.getPlayer(), doVerticalOffset); if (useContext.getPlayer() != null) { if (!useContext.getPlayer().isCreative()) { itemStack.shrink(1); } } } return InteractionResult.CONSUME; } private int getSpecies(ItemStack itemIn) { if (itemIn.getTag() != null && itemIn.getTag().contains("CustomModelData")) { return itemIn.getTag().getInt("CustomModelData"); } UntamedWilds.LOGGER.error("No variant found in this itemstack NBT data"); return 0; } public void fillItemCategory(CreativeModeTab group, NonNullList<ItemStack> items) { if (group == ModCreativeModeTab.untamedwilds_items) { for(int i = 0; i < EntityUtils.getNumberOfSpecies(this.entity.get()); i++) { CompoundTag baseTag = new CompoundTag(); ItemStack item = new ItemStack(this); baseTag.putInt("variant", i); baseTag.putInt("CustomModelData", i); item.setTag(baseTag); items.add(item); } } } }
4,362
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
LookThroughSpyglassEvent.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/LookThroughSpyglassEvent.java
package untamedwilds.item; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextComponent; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.ProjectileUtil; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ISpecies; import untamedwilds.entity.relict.EntitySpitter; import untamedwilds.init.ModAdvancementTriggers; @Mod.EventBusSubscriber(modid = UntamedWilds.MOD_ID) public class LookThroughSpyglassEvent { @SubscribeEvent public static void lookAtEntityThroughSpyglassEvent(LivingEntityUseItemEvent event) { ItemStack usedItem = event.getItem(); Entity entity = event.getEntity(); if (ConfigGamerules.spyglassBehaviorChange.get() && !entity.getLevel().isClientSide && entity instanceof Player playerIn && playerIn.tickCount % 20 == 0 && usedItem.getItem().equals(Items.SPYGLASS)) { HitResult hitresult = raycast(playerIn, ConfigGamerules.spyglassCheckRange.get(), true); if (hitresult.getType() == HitResult.Type.ENTITY) { EntityHitResult entityHitResult = (EntityHitResult)hitresult; if (entityHitResult.getEntity() instanceof LivingEntity livingEntityHitResult) { displayEntityData(livingEntityHitResult, playerIn, playerIn.getLevel()); // TODO: Hardcoded list of "observing" advancements if (entityHitResult.getEntity() instanceof EntitySpitter) ModAdvancementTriggers.DISCOVERED_SPITTER.trigger((ServerPlayer) playerIn); } } } } public static HitResult raycast(Entity origin, double maxDistance, boolean hitsEntities) { Vec3 startPos = origin.getEyePosition(1F); Vec3 rotation = origin.getViewVector(1F); Vec3 endPos = startPos.add(rotation.x * maxDistance, rotation.y * maxDistance, rotation.z * maxDistance); HitResult hitResult = origin.level.clip(new ClipContext(startPos, endPos, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, origin)); if(hitResult.getType() != HitResult.Type.MISS) endPos = hitResult.getLocation(); maxDistance *= 5; HitResult entityHitResult = ProjectileUtil.getEntityHitResult(origin, startPos, endPos, origin.getBoundingBox().expandTowards(rotation.scale(maxDistance)).inflate(1.0D, 1.0D, 1.0D), entity -> !entity.isSpectator(), maxDistance); if(hitsEntities && entityHitResult != null) hitResult = entityHitResult; return hitResult; } private static void displayEntityData(LivingEntity target, Player playerIn, Level world) { TextComponent name = new TextComponent(""); if (target instanceof ComplexMob entity) { String entityName = entity instanceof ISpecies ? ((ISpecies) entity).getSpeciesName() : entity.getName().getString(); name.append((entity.isBaby() ? "Young " : "") + (ConfigGamerules.genderedBreeding.get() ? entity.getGenderString() + " " : "") + entityName + " "); if (ConfigGamerules.scientificNames.get()) { String useVarName = entity instanceof ISpecies ? "_" + ((ISpecies) entity).getRawSpeciesName(entity.getVariant()) : ""; name.append("("); name.append(new TranslatableComponent(entity.getType().getDescriptionId() + useVarName + ".sciname").withStyle(ChatFormatting.ITALIC)); name.append(") "); } if (!entity.isMale() && entity.getAge() > 0 && !ConfigGamerules.easyBreeding.get()) { name.append("This female is pregnant "); } } else { name.append(target.isBaby() ? "Young " : "" + target.getName().getString() + " "); } if (true) { int health = (int) (10 * target.getHealth() / target.getMaxHealth()); MutableComponent state = getHealthState(health); name.append("("); name.append(state); name.append(") "); } if (true) { name.append("("); name.append(getThreatLevel(target, playerIn)); name.append(")"); } playerIn.displayClientMessage(name, true); } private static MutableComponent getHealthState(int health) { switch (health) { case 10, 9, 8 -> { return new TextComponent("Healthy").withStyle(ChatFormatting.GREEN); } case 7, 6, 5 -> { return new TextComponent("Injured").withStyle(ChatFormatting.YELLOW); } case 4, 3, 2 -> { return new TextComponent("Wounded").withStyle(ChatFormatting.RED); } case 1, 0 -> { return new TextComponent("Almost Dead").withStyle(ChatFormatting.DARK_RED); } } return new TextComponent(""); } private static MutableComponent getThreatLevel(LivingEntity target, Player player) { int val = ComplexMob.getEcoLevel(player) - ComplexMob.getEcoLevel(target); if (val > 4) return new TextComponent("Harmless").withStyle(ChatFormatting.GREEN); else if (val > 2) return new TextComponent("Mild threat").withStyle(ChatFormatting.YELLOW); else if (val > 0) return new TextComponent("Caution").withStyle(ChatFormatting.YELLOW); else if (val > -4) return new TextComponent("Dangerous").withStyle(ChatFormatting.RED); else return new TextComponent("Deadly").withStyle(ChatFormatting.DARK_RED); } }
6,436
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
UntamedSpawnEggItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/UntamedSpawnEggItem.java
package untamedwilds.item; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.BaseSpawner; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.SpawnData; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.SpawnerBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.BlockHitResult; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.ForgeSpawnEggItem; import untamedwilds.entity.ComplexMob; import untamedwilds.util.EntityUtils; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; public class UntamedSpawnEggItem extends ForgeSpawnEggItem { private int currentSpecies; private boolean isCached; private final Supplier<? extends EntityType<? extends Mob>> entityType; public UntamedSpawnEggItem(Supplier<? extends EntityType<? extends Mob>> typeIn, int primaryColorIn, int secondaryColorIn, Properties builder) { super(typeIn, primaryColorIn, secondaryColorIn, builder); this.currentSpecies = 0; this.entityType = typeIn; this.isCached = false; } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { tooltip.add(new TranslatableComponent("item.untamedwilds.spawn_egg_info").withStyle(ChatFormatting.GRAY)); tooltip.add(new TranslatableComponent("item.untamedwilds.spawn_egg_current", this.getCurrentSpeciesName(stack)).withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY)); } private String getCurrentSpeciesName(ItemStack stack) { if (!this.isCached && stack.hasTag()) { if (stack.getTag().contains("EntityTag")) { this.currentSpecies = stack.getTag().getCompound("EntityTag").getInt("Variant"); this.isCached = true; } } int i = this.currentSpecies - 1; return i >= 0 ? EntityUtils.getVariantName(this.entityType.get(), i) + " (" + i + ")" : "Random"; } public void increaseSpeciesNumber(int intIn) { this.currentSpecies = (intIn % (ComplexMob.getEntityData(this.entityType.get()).getSpeciesData().size() + 1)); this.isCached = true; } @Override public InteractionResultHolder<ItemStack> use(Level worldIn, Player playerIn, InteractionHand handIn) { ItemStack itemstack = playerIn.getItemInHand(handIn); if (!(worldIn instanceof ServerLevel)) { return InteractionResultHolder.success(itemstack); } if (playerIn.isSteppingCarefully()) { this.increaseSpeciesNumber(this.currentSpecies + 1); playerIn.displayClientMessage(new TranslatableComponent("item.untamedwilds.spawn_egg_change", this.getCurrentSpeciesName(itemstack)), true); itemstack.setTag(new CompoundTag()); if (this.currentSpecies != 0) { CompoundTag entityNBT = new CompoundTag(); entityNBT.putInt("Variant", this.currentSpecies - 1); itemstack.getTag().put("EntityTag", entityNBT); } return InteractionResultHolder.pass(itemstack); } BlockHitResult raytraceresult = getPlayerPOVHitResult(worldIn, playerIn, ClipContext.Fluid.SOURCE_ONLY); if (raytraceresult.getType() != BlockHitResult.Type.BLOCK) { return InteractionResultHolder.pass(itemstack); } else { BlockPos blockpos = raytraceresult.getBlockPos(); if (!(worldIn.getBlockState(blockpos).getBlock() instanceof LiquidBlock)) { return InteractionResultHolder.pass(itemstack); } else if (worldIn.mayInteract(playerIn, blockpos) && playerIn.mayUseItemAt(blockpos, raytraceresult.getDirection(), itemstack)) { Integer species = this.currentSpecies - 1 < 0 ? null : this.currentSpecies - 1; EntityUtils.createMobFromItem((ServerLevel) worldIn, itemstack, this.entityType.get(), species, blockpos, playerIn, false, true); playerIn.awardStat(Stats.ITEM_USED.get(this)); worldIn.gameEvent(GameEvent.ENTITY_PLACE, playerIn); return InteractionResultHolder.consume(itemstack); } else { return InteractionResultHolder.fail(itemstack); } } } @Override public InteractionResult useOn(UseOnContext useContext) { Level world = useContext.getLevel(); if (!(world instanceof ServerLevel)) { return InteractionResult.SUCCESS; } else { ItemStack itemstack = useContext.getItemInHand(); BlockPos blockpos = useContext.getClickedPos(); Direction direction = useContext.getClickedFace(); BlockState blockstate = world.getBlockState(blockpos); if (blockstate.is(Blocks.SPAWNER)) { BlockEntity tileentity = world.getBlockEntity(blockpos); if (tileentity instanceof SpawnerBlockEntity) { BaseSpawner abstractspawner = ((SpawnerBlockEntity)tileentity).getSpawner(); EntityType<?> entitytype1 = this.getType(itemstack.getTag()); abstractspawner.setEntityId(entitytype1); CompoundTag entityNBT_2 = new CompoundTag(); entityNBT_2.putString("id", entitytype1.getRegistryName().toString()); if (this.currentSpecies - 1 >= 0) { entityNBT_2.putInt("Variant", this.currentSpecies - 1); entityNBT_2.putFloat("Size", ComplexMob.getEntityData(entitytype1).getScale(this.currentSpecies - 1)); } else { entityNBT_2.putFloat("Size", 1); } abstractspawner.setNextSpawnData(world, blockpos, new SpawnData(entityNBT_2, Optional.empty())); tileentity.setChanged(); world.sendBlockUpdated(blockpos, blockstate, blockstate, 3); itemstack.shrink(1); return InteractionResult.CONSUME; } } BlockPos blockpos1; if (blockstate.getCollisionShape(world, blockpos).isEmpty()) { blockpos1 = blockpos; } else { blockpos1 = blockpos.relative(direction); } if (!itemstack.hasTag()) itemstack.setTag(new CompoundTag()); Entity spawn = this.entityType.get().create((ServerLevel) world, itemstack.getTag(), null, useContext.getPlayer(), blockpos, MobSpawnType.SPAWN_EGG, true, !Objects.equals(blockpos, blockpos1) && direction == Direction.UP); if (spawn == null) { return InteractionResult.PASS; } //BlockPos spawnPos = blockstate.getCollisionShape(world, blockpos).isEmpty() ? blockpos : blockpos.relative(direction); Integer species = this.currentSpecies - 1 < 0 ? null : this.currentSpecies - 1; EntityUtils.createMobFromItem((ServerLevel) world, itemstack, this.entityType.get(), species, blockpos1, useContext.getPlayer(), false, true); if (useContext.getPlayer() != null) { itemstack.shrink(1); world.gameEvent(useContext.getPlayer(), GameEvent.ENTITY_PLACE, blockpos); } return InteractionResult.CONSUME; } } }
8,359
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
MobBucketedItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/MobBucketedItem.java
package untamedwilds.item; import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.util.EntityUtils; import untamedwilds.util.ModCreativeModeTab; import javax.annotation.Nullable; import java.util.List; import java.util.function.Supplier; public class MobBucketedItem extends BucketItem { private final Supplier<? extends EntityType<?>> entity; public MobBucketedItem(Supplier<? extends EntityType<?>> typeIn, Fluid fluid, Item.Properties builder) { super(() -> fluid, builder); this.entity = typeIn; } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { if (ComplexMob.ENTITY_DATA_HASH.containsKey(this.entity.get())) { EntityUtils.buildTooltipData(stack, tooltip, this.entity.get(), EntityUtils.getVariantName(this.entity.get(), this.getSpecies(stack))); } } public Component getName(ItemStack stack) { if (ComplexMob.ENTITY_DATA_HASH.containsKey(this.entity.get())) { return new TranslatableComponent("item.untamedwilds.bucket_" + this.entity.get().getRegistryName().getPath() + "_" + EntityUtils.getVariantName(this.entity.get(), this.getSpecies(stack))); } return super.getName(stack); } public void checkExtraContent(@Nullable Player playerIn, Level worldIn, ItemStack itemStackIn, BlockPos posIn) { if (worldIn instanceof ServerLevel) { this.spawn(worldIn, itemStackIn, posIn); worldIn.gameEvent(playerIn, GameEvent.ENTITY_PLACE, posIn); } } public void spawn(Level worldIn, ItemStack itemStack, BlockPos pos) { if (worldIn instanceof ServerLevel) { EntityType<?> entity = EntityUtils.getEntityTypeFromTag(itemStack.getTag(), this.entity.get()); EntityUtils.createMobFromItem((ServerLevel) worldIn, itemStack, entity, this.getSpecies(itemStack), pos, null, false); } } protected void playEmptySound(@Nullable Player player, LevelAccessor worldIn, BlockPos pos) { worldIn.playSound(player, pos, SoundEvents.BUCKET_EMPTY_FISH, SoundSource.NEUTRAL, 1.0F, 1.0F); } private int getSpecies(ItemStack itemIn) { if (itemIn.getTag() != null && itemIn.getTag().contains("CustomModelData")) { return itemIn.getTag().getInt("CustomModelData"); } UntamedWilds.LOGGER.error("No variant found in this itemstack NBT data"); return 0; } public void fillItemCategory(CreativeModeTab group, NonNullList<ItemStack> items) { if (group == ModCreativeModeTab.untamedwilds_items) { for(int i = 0; i < EntityUtils.getNumberOfSpecies(this.entity.get()); i++) { CompoundTag baseTag = new CompoundTag(); ItemStack item = new ItemStack(this); baseTag.putInt("variant", i); baseTag.putInt("CustomModelData", i); item.setTag(baseTag); items.add(item); } } } }
4,000
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
OwnershipDeedItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/OwnershipDeedItem.java
package untamedwilds.item; import net.minecraft.ChatFormatting; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.UUID; public class OwnershipDeedItem extends Item { public OwnershipDeedItem(Properties properties) { super(properties); } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { if (stack.hasTag()) { CompoundTag nbt = stack.getTag(); tooltip.add(new TranslatableComponent("item.untamedwilds.ownership_deed_desc_4", nbt.getString("entityname")).withStyle(ChatFormatting.GRAY)); tooltip.add(new TranslatableComponent("item.untamedwilds.ownership_deed_desc_5").withStyle(ChatFormatting.GRAY)); tooltip.add(new TranslatableComponent("item.untamedwilds.ownership_deed_desc_6", nbt.getString("ownername")).withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY)); } else { tooltip.add(new TranslatableComponent("item.untamedwilds.ownership_deed_desc_1").withStyle(ChatFormatting.GRAY)); } } public boolean isFoil(ItemStack stack) { return stack.hasTag(); } @Nonnull public InteractionResultHolder<ItemStack> use(Level worldIn, Player playerIn, InteractionHand handIn) { ItemStack itemstack = playerIn.getItemInHand(handIn); if (itemstack.hasTag()) { CompoundTag nbt = itemstack.getTag(); if (!nbt.getString("entityid").isEmpty()) { List<LivingEntity> list = worldIn.getEntitiesOfClass(LivingEntity.class, playerIn.getBoundingBox().inflate(8.0D)); for(LivingEntity entity : list) { if (entity.getUUID().equals(UUID.fromString(nbt.getString("entityid")))) { entity.addEffect(new MobEffectInstance(MobEffects.GLOWING, 80, 0, false, false)); } } } } return new InteractionResultHolder<>(InteractionResult.SUCCESS, itemstack); } /*@Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, Hand hand) { UntamedWilds.LOGGER.log(Level.INFO, "Trying to get entity"); ItemStack itemstack = playerIn.getItemInHand(hand); if (target instanceof TameableEntity) { TameableEntity entity_target = (TameableEntity) target; if (entity_target.isTame()) { if (entity_target.getOwnerId().equals(playerIn.getUUID()) && !itemstack.hasTag()) { CompoundTag nbt = new CompoundTag(); nbt.putString("ownername", playerIn.getName().getString()); nbt.putString("entityname", entity_target.getName().getString()); nbt.putString("ownerid", playerIn.getUUID().toString()); nbt.putString("entityid", entity_target.getUUID().toString()); itemstack.setTag(nbt); if (UntamedWilds.DEBUG) { UntamedWilds.LOGGER.log(Level.INFO, "Pet owner signed a deed for a " + entity_target.getName().getString()); } return InteractionResult.SUCCESS; } else if (itemstack.hasTag()) { if (entity_target.getOwnerId().toString().equals(itemstack.getTag().getString("ownerid")) && entity_target.getUUID().toString().equals(itemstack.getTag().getString("entityid"))) { entity_target.setOwnerId(playerIn.getUUID()); if (!playerIn.isCreative()) { itemstack.shrink(1); } // playerIn.addStat(Stats.getObjectUseStats(this)); if (UntamedWilds.DEBUG) { UntamedWilds.LOGGER.log(Level.INFO, "Pet ownership transferred to " + playerIn.getName().getString()); } return InteractionResult.CONSUME; } } return InteractionResult.FAIL; } } return InteractionResult.FAIL; }*/ }
5,036
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
MobBottledItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/MobBottledItem.java
package untamedwilds.item; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.util.EntityUtils; import untamedwilds.util.ModCreativeModeTab; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.function.Supplier; public class MobBottledItem extends Item { private final Supplier<? extends EntityType<?>> entity; public MobBottledItem(Supplier<? extends EntityType<?>> typeIn, Properties properties) { super(properties); this.entity = typeIn; } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { EntityUtils.buildTooltipData(stack, tooltip, this.entity.get(), EntityUtils.getVariantName(this.entity.get(), this.getSpecies(stack))); } public Component getName(ItemStack stack) { return new TranslatableComponent("item.untamedwilds.bottle_" + this.entity.get().getRegistryName().getPath() + "_" + EntityUtils.getVariantName(this.entity.get(), this.getSpecies(stack))); } @Override public InteractionResult useOn(UseOnContext useContext) { Level worldIn = useContext.getLevel(); if (!(worldIn instanceof ServerLevel)) { return InteractionResult.SUCCESS; } else { ItemStack itemStack = useContext.getItemInHand(); BlockPos pos = useContext.getClickedPos(); Direction facing = useContext.getClickedFace(); BlockState blockState = worldIn.getBlockState(pos); BlockPos spawnPos = blockState.getCollisionShape(worldIn, pos).isEmpty() ? pos : pos.relative(facing); EntityType<?> entity = EntityUtils.getEntityTypeFromTag(itemStack.getTag(), this.entity.get()); boolean doVerticalOffset = !Objects.equals(pos, spawnPos) && facing == Direction.UP; EntityUtils.createMobFromItem((ServerLevel) worldIn, itemStack, entity, this.getSpecies(itemStack), spawnPos, useContext.getPlayer(), doVerticalOffset); if (useContext.getPlayer() != null) { if (!useContext.getPlayer().isCreative()) { itemStack.shrink(1); useContext.getPlayer().getInventory().add(new ItemStack(Items.GLASS_BOTTLE)); } } } return InteractionResult.CONSUME; } private int getSpecies(ItemStack itemIn) { if (itemIn.getTag() != null && itemIn.getTag().contains("CustomModelData")) { return itemIn.getTag().getInt("CustomModelData"); } UntamedWilds.LOGGER.error("No variant found in this itemstack NBT data"); return 0; } public void fillItemCategory(CreativeModeTab group, NonNullList<ItemStack> items) { if (group == ModCreativeModeTab.untamedwilds_items) { for(int i = 0; i < EntityUtils.getNumberOfSpecies(this.entity.get()); i++) { CompoundTag baseTag = new CompoundTag(); ItemStack item = new ItemStack(this); baseTag.putInt("variant", i); baseTag.putInt("CustomModelData", i); item.setTag(baseTag); items.add(item); } } } }
4,104
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
MobEggItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/MobEggItem.java
package untamedwilds.item; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.util.EntityUtils; import untamedwilds.util.ModCreativeModeTab; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.function.Supplier; public class MobEggItem extends Item { private final Supplier<? extends EntityType<?>> entity; public MobEggItem(Supplier<? extends EntityType<?>> typeIn, Properties properties) { super(properties); this.entity = typeIn; } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { tooltip.add(new TranslatableComponent("mobspawn.tooltip.unknown").withStyle(ChatFormatting.GRAY)); } @Override public InteractionResult useOn(UseOnContext useContext) { Level worldIn = useContext.getLevel(); if (!(worldIn instanceof ServerLevel)) { return InteractionResult.SUCCESS; } else { ItemStack itemStack = useContext.getItemInHand(); BlockPos pos = useContext.getClickedPos(); Direction facing = useContext.getClickedFace(); BlockState blockState = worldIn.getBlockState(pos); BlockPos spawnPos = blockState.getCollisionShape(worldIn, pos).isEmpty() ? pos : pos.relative(facing); EntityType<?> entity = EntityUtils.getEntityTypeFromTag(itemStack.getTag(), this.entity.get()); Entity spawn = entity.create((ServerLevel) worldIn, itemStack.getTag(), null, useContext.getPlayer(), spawnPos, MobSpawnType.BUCKET, true, !Objects.equals(pos, spawnPos) && facing == Direction.UP); if (spawn instanceof ComplexMob) { ComplexMob entitySpawn = (ComplexMob) spawn; entitySpawn.setVariant(this.getSpecies(itemStack, entitySpawn)); entitySpawn.chooseSkinForSpecies(entitySpawn, true); entitySpawn.setRandomMobSize(); entitySpawn.setGender(entitySpawn.getRandom().nextInt(2)); entitySpawn.setAge(entitySpawn.getAdulthoodTime() * -1); if (spawn instanceof INeedsPostUpdate) { ((INeedsPostUpdate) spawn).updateAttributes(); } } if (spawn != null) { ((ServerLevel) worldIn).addFreshEntityWithPassengers(spawn); } itemStack.shrink(1); } return InteractionResult.CONSUME; } public String getDescriptionId() { return new TranslatableComponent("item.untamedwilds.egg_" + this.entity.get().getRegistryName().getPath()).getString(); } private int getSpecies(ItemStack itemIn, ComplexMob entityIn) { if (itemIn.getTag() != null && itemIn.getTag().contains("variant")) { return itemIn.getTag().getInt("variant"); } return entityIn.getVariant(); } public void fillItemCategory(CreativeModeTab group, NonNullList<ItemStack> items) { if (group == ModCreativeModeTab.untamedwilds_items) { for(int i = 0; i < EntityUtils.getNumberOfSpecies(this.entity.get()); i++) { CompoundTag baseTag = new CompoundTag(); ItemStack item = new ItemStack(this); baseTag.putInt("variant", i); baseTag.putInt("CustomModelData", i); item.setTag(baseTag); items.add(item); } } } // TODO: Have dropped eggs eventually hatch into baby mobs /*@Override public void onDestroyed(ItemEntity entityItem) { ItemStack itemstack = entityItem.getItem(); Level worldIn = entityItem.world; if (entityItem.world.isClientSide || entityItem.tickCount < this.getHatchingTime(itemstack)) { return super.onEntityItemUpdate(entityItem); } Entity entity = EntityList.createEntityByIDFromName(this.entity, worldIn);; if (entity instanceof ComplexMob) { ComplexMob entitySpawn = (ComplexMob) entity; entitySpawn.setSpecies(this.getSpecies(itemstack)); entitySpawn.setPosition(entityItem.getPosition().getX() + 0.5, entityItem.getPosition().getY() + 1, entityItem.getPosition().getZ() + 0.5); entitySpawn.setRandomMobSize(); entitySpawn.setGender(worldIn.random.nextInt(2)); itemstack.shrink(1); if (itemstack.isEmpty()) { entityItem.setDead(); } worldIn.spawnEntity(entitySpawn); entitySpawn.playLivingSound(); } return super.onEntityItemUpdate(entityItem); }*/ }
5,699
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ChumItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/ChumItem.java
package untamedwilds.item; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.stats.Stats; import net.minecraft.tags.FluidTags; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.animal.WaterAnimal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.UseAnim; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMobAmphibious; import untamedwilds.entity.ComplexMobAquatic; import untamedwilds.init.ModAdvancementTriggers; import untamedwilds.init.ModParticles; import java.util.ArrayList; import java.util.List; public class ChumItem extends Item { public ChumItem(Properties builder) { super(builder); } public int getUseDuration(ItemStack stack) { return 40; } public UseAnim getUseAnimation(ItemStack stack) { return UseAnim.EAT; } public InteractionResultHolder<ItemStack> use(Level worldIn, Player playerIn, InteractionHand handIn) { BlockHitResult blockraytraceresult = getPlayerPOVHitResult(worldIn, playerIn, ClipContext.Fluid.SOURCE_ONLY); if (worldIn.getFluidState(blockraytraceresult.getBlockPos()).is(FluidTags.WATER)) { ItemStack itemstack = playerIn.getItemInHand(handIn); playerIn.getCooldowns().addCooldown(this, 30); worldIn.playSound(playerIn, playerIn.blockPosition(), SoundEvents.FISHING_BOBBER_SPLASH, SoundSource.NEUTRAL, 1F, 1F); if (!worldIn.isClientSide) { Vec3 pos = blockraytraceresult.getLocation(); for (int i = 0; i < 6; i++) { double d2 = worldIn.random.nextGaussian() * 0.03D; double d3 = worldIn.random.nextGaussian() * 0.03D; double d4 = worldIn.random.nextGaussian() * 0.03D; ((ServerLevel)worldIn).sendParticles(ModParticles.CHUM_DISPERSE, pos.x, pos.y - 0.1F, pos.z, 1, d2, d3, d4, 0.02D); } ModAdvancementTriggers.BAIT_BASIC.trigger((ServerPlayer) playerIn); playerIn.awardStat(Stats.ITEM_USED.get(this)); if (!playerIn.isCreative()) { itemstack.shrink(1); } // Currently, using Chum will lure all nearby water mobs into the used location through a single tryMoveToXYZ float dist = 80; List<Entity> list = worldIn.getEntities(playerIn, (new AABB(playerIn.getX(), playerIn.getY(), playerIn.getZ(), playerIn.getX() + 1.0D, playerIn.getY() + 1.0D, playerIn.getZ() + 1.0D)).inflate(dist)); List<Mob> waterMobs = new ArrayList<>(); for (Entity entity : list) { if ((entity instanceof WaterAnimal || entity instanceof ComplexMobAquatic || entity instanceof ComplexMobAmphibious) && entity.isInWater()) waterMobs.add((Mob) entity); } if (waterMobs.size() >= 100) { ModAdvancementTriggers.MASTER_BAIT.trigger((ServerPlayer) playerIn); } for (Mob waterMob : waterMobs) { if (UntamedWilds.DEBUG) waterMob.addEffect(new MobEffectInstance(MobEffects.GLOWING, 60, 0, true, false)); waterMob.getNavigation().stop(); waterMob.getNavigation().moveTo(pos.x, pos.y, pos.z, 1); } } return InteractionResultHolder.consume(itemstack); } // TODO: Maybe make Sharks in an AoE aggressive and/or spawn new mobs from the Large Ocean pool? return InteractionResultHolder.pass(playerIn.getItemInHand(handIn)); /*InteractionResult actionresulttype = super.use(new InteractionResultHolder(playerIn, handIn, blockraytraceresult1)); return new InteractionResultHolder<>(actionresulttype, playerIn.getItemInHand(handIn));*/ } }
4,620
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
LardItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/LardItem.java
package untamedwilds.item; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemUtils; import net.minecraft.world.item.UseAnim; import net.minecraft.world.level.Level; public class LardItem extends Item { public LardItem(Item.Properties builder) { super(builder); } public int getUseDuration(ItemStack stack) { return 40; } public UseAnim getUseAnimation(ItemStack p_41358_) { return UseAnim.EAT; } public SoundEvent getDrinkingSound() { return SoundEvents.HONEY_DRINK; } public SoundEvent getEatingSound() { return SoundEvents.HONEY_DRINK; } public InteractionResultHolder<ItemStack> use(Level p_41352_, Player p_41353_, InteractionHand p_41354_) { return ItemUtils.startUsingInstantly(p_41352_, p_41353_, p_41354_); } }
1,114
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EraserItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/debug/EraserItem.java
package untamedwilds.item.debug; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionHand; public class EraserItem extends Item { public EraserItem(Properties properties) { super(properties); } @Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, InteractionHand hand) { if (target.getLevel().isClientSide) return InteractionResult.PASS; target.remove(Entity.RemovalReason.DISCARDED); return InteractionResult.SUCCESS; } }
788
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
IpecacItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/debug/IpecacItem.java
package untamedwilds.item.debug; import net.minecraft.network.chat.TextComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import untamedwilds.entity.ComplexMobTerrestrial; public class IpecacItem extends Item { public IpecacItem(Properties properties) { super(properties); } @Override public InteractionResult useOn(UseOnContext context) { context.getPlayer().sendMessage(new TextComponent("Pos: " + context.getClickedPos()), context.getPlayer().getUUID()); return InteractionResult.PASS; } @Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, InteractionHand hand) { if (target.getLevel().isClientSide) return InteractionResult.PASS; if (target instanceof Player/* || !target.isNonBoss()*/) return InteractionResult.FAIL; if (target instanceof ComplexMobTerrestrial) { ComplexMobTerrestrial entity = (ComplexMobTerrestrial)target; entity.addHunger(-100); entity.huntingCooldown = 0; return InteractionResult.SUCCESS; } return InteractionResult.FAIL; } }
1,443
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
HighlighterItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/debug/HighlighterItem.java
package untamedwilds.item.debug; import net.minecraft.client.Minecraft; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.InteractionResult; import net.minecraft.world.level.Level; public class HighlighterItem extends Item { public HighlighterItem(Properties properties) { super(properties); } public InteractionResultHolder<ItemStack> use(Level worldIn, Player playerIn, InteractionHand handIn) { if (playerIn.isSteppingCarefully() && worldIn.isClientSide) { Minecraft.getInstance().getEntityRenderDispatcher().setRenderHitBoxes(!Minecraft.getInstance().getEntityRenderDispatcher().shouldRenderHitBoxes()); } return super.use(worldIn, playerIn, handIn); } @Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, InteractionHand hand) { if (target.getLevel().isClientSide) return InteractionResult.PASS; target.addEffect(new MobEffectInstance(MobEffects.GLOWING, 999999, 0, true, false)); return InteractionResult.SUCCESS; } }
1,432
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
GrowthTonicItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/debug/GrowthTonicItem.java
package untamedwilds.item.debug; import net.minecraft.world.entity.AgeableMob; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionHand; import untamedwilds.entity.ComplexMob; public class GrowthTonicItem extends Item { public GrowthTonicItem(Properties properties) { super(properties); } @Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, InteractionHand hand) { if (target.getLevel().isClientSide) return InteractionResult.PASS; if (target instanceof Player/* || !target.isNonBoss()*/) return InteractionResult.FAIL; if (target instanceof ComplexMob && !target.isBaby()) { float prevSize = ((ComplexMob) target).getMobSize(); ((ComplexMob) target).setMobSize(prevSize + 0.1F); return InteractionResult.SUCCESS; } if (target instanceof AgeableMob && target.isBaby()) { ((AgeableMob) target).setAge(0); return InteractionResult.SUCCESS; } return InteractionResult.FAIL; } }
1,291
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
LovePotionItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/debug/LovePotionItem.java
package untamedwilds.item.debug; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionHand; import untamedwilds.entity.ComplexMob; public class LovePotionItem extends Item { public LovePotionItem(Properties properties) { super(properties); } @Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, InteractionHand hand) { if (target.getLevel().isClientSide) return InteractionResult.PASS; if (target instanceof Player/* || !target.isNonBoss()*/) return InteractionResult.FAIL; if (target instanceof ComplexMob) { if (((ComplexMob) target).getAge() > 0) { ((ComplexMob) target).setAge(1); } else { ComplexMob entity = (ComplexMob)target; entity.setInLove(playerIn); //entity.breed(); //entity.setAge(60); return InteractionResult.SUCCESS; } } if (target instanceof Animal) { ((Animal) target).setInLove(playerIn); return InteractionResult.SUCCESS; } return InteractionResult.FAIL; } }
1,452
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
AnalyzerItem.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/item/debug/AnalyzerItem.java
package untamedwilds.item.debug; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.TextComponent; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.AgeableMob; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BowItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.ComplexMobTerrestrial; import untamedwilds.entity.ISpecies; import untamedwilds.util.TimeUtils; public class AnalyzerItem extends Item { public AnalyzerItem(Properties properties) { super(properties); } @Override public InteractionResult interactLivingEntity(ItemStack stack, Player playerIn, LivingEntity target, InteractionHand hand) { Level world = target.getLevel(); if (world.isClientSide) return InteractionResult.PASS; if (target instanceof ComplexMob) { ComplexMob entity = (ComplexMob)target; String entityName = entity instanceof ISpecies ? ((ISpecies) entity).getSpeciesName() : entity.getName().getString(); playerIn.sendMessage(new TextComponent("Diagnose: " + (ConfigGamerules.genderedBreeding.get() ? entity.getGenderString() + " " : "") + entityName + " (Skin: " + entity.getSkin() + ") (Eco Level: " + ComplexMob.getEcoLevel(entity) + ") " + entity.getHealth() + "/" + entity.getMaxHealth() + " HP"), playerIn.getUUID()); if (ConfigGamerules.scientificNames.get()) { String useVarName = entity instanceof ISpecies ? "_" + ((ISpecies) entity).getRawSpeciesName(entity.getVariant()) : ""; playerIn.sendMessage(new TranslatableComponent(entity.getType().getDescriptionId() + useVarName + ".sciname").withStyle(ChatFormatting.ITALIC), playerIn.getUUID()); } if (target instanceof ComplexMobTerrestrial) { playerIn.sendMessage(new TextComponent("Hunger: " + ((ComplexMobTerrestrial)entity).getHunger() + "/100 Hunger"), playerIn.getUUID()); } if (!entity.isMale() && entity.getAge() > 0 && !ConfigGamerules.easyBreeding.get()) { playerIn.sendMessage(new TextComponent("This female will give birth in " + TimeUtils.convertTicksToDays(world, entity.getAge()) + " (" + entity.getAge() + " ticks)"), playerIn.getUUID()); } if (entity.wantsToBreed()) { playerIn.sendMessage(new TextComponent("This mob is looking for a suitable mate"), playerIn.getUUID()); } if (entity.isBaby()) { playerIn.sendMessage(new TextComponent("This mob will grow up in " + TimeUtils.convertTicksToDays(world, entity.getAge() * -1) + " (" + entity.getAge() * -1 + " ticks)"), playerIn.getUUID()); } //playerIn.sendMessage(new StringTextComponent("This mob will naturally despawn: " + !entity.preventDespawn())); return InteractionResult.SUCCESS; } else { playerIn.sendMessage(new TextComponent("Diagnose: " + target.getName().getString() + " " + target.getHealth() + "/" + target.getMaxHealth() + " HP (Eco Level: " + ComplexMob.getEcoLevel(target) + ")"), playerIn.getUUID()); if (target.isBaby() && target instanceof AgeableMob) { AgeableMob entity = (AgeableMob) target; playerIn.sendMessage(new TextComponent("This mob will grow up in " + TimeUtils.convertTicksToDays(world, entity.getAge() * -1) + " (" + entity.getAge() * -1 + " ticks)"), playerIn.getUUID()); } return InteractionResult.SUCCESS; } } }
3,909
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CompatBridge.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/compat/CompatBridge.java
package untamedwilds.compat; import net.minecraftforge.fml.ModList; import org.apache.logging.log4j.Level; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigModCompat; public class CompatBridge { private static final String SERENSEASONS_MODID = "sereneseasons"; private static final String PATCHOULI_MODID = "patchouli"; public static boolean Patchouli = false; // Used as a fallback to unlock the Root advancement if there's no EoL public static boolean SereneSeasons = false; // TBI: Integrate seasons into mob behaviors public static void RegisterCompat() { if (ModList.get().isLoaded(SERENSEASONS_MODID) && ConfigModCompat.sereneSeasonsCompat.get()) { SereneSeasons = true; UntamedWilds.LOGGER.log(Level.INFO, "Loading compatibility module with SereneSeasons"); } if (ModList.get().isLoaded(PATCHOULI_MODID) && ConfigModCompat.sereneSeasonsCompat.get()) { Patchouli = true; UntamedWilds.LOGGER.log(Level.INFO, "Loading compatibility module with Patchouli"); } } }
1,094
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CompatSereneSeasons.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/compat/CompatSereneSeasons.java
package untamedwilds.compat; import net.minecraft.world.level.Level; public class CompatSereneSeasons { public static boolean isCurrentSeason(Level world, String string) { return true; } /*ISeasonState data = SeasonHelper.getSeasonState(world); String season = data.getSeason().toString(); if (string.equals("ALL")) { return true; } if (season.equals(string)) { return true; } String subseason = data.getSubSeason().toString(); if (subseason.equals(string)) { return true; } String tropicalseason = data.getTropicalSeason().toString(); return tropicalseason.equals(string); } public static int getDayLength(World world) { return SeasonHelper.getSeasonState(world).getDayDuration(); } public static int getDaysInMonth(World world) { return SeasonHelper.getSeasonState(world).getSubSeasonDuration() / getDayLength(world); } public static int getTicksInMonth(World world) { return SeasonHelper.getSeasonState(world).getSubSeasonDuration(); }*/ }
1,139
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ModEntityRightClickEvent.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/ModEntityRightClickEvent.java
package untamedwilds.util; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.TamableAnimal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.InteractionHand; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import org.apache.logging.log4j.Level; import untamedwilds.UntamedWilds; import untamedwilds.init.ModItems; import java.util.Objects; @Mod.EventBusSubscriber(modid = UntamedWilds.MOD_ID) public class ModEntityRightClickEvent { @SubscribeEvent public static void modEntityRightClickEvent(PlayerInteractEvent.EntityInteract event) { Player playerIn = event.getPlayer(); Entity target = event.getTarget(); InteractionHand hand = event.getHand(); if (/*!event.getWorld().isClientSide && hand == InteractionHand.MAIN_HAND &&*/ playerIn.getItemInHand(InteractionHand.MAIN_HAND).getItem() == ModItems.OWNERSHIP_DEED.get()) { ItemStack itemstack = playerIn.getItemInHand(hand); if (target instanceof TamableAnimal) { TamableAnimal entity_target = (TamableAnimal) target; if (entity_target.isTame()) { if (Objects.equals(entity_target.getOwnerUUID(), playerIn.getUUID()) && !itemstack.hasTag()) { CompoundTag nbt = new CompoundTag(); nbt.putString("ownername", playerIn.getName().getString()); nbt.putString("entityname", entity_target.getName().getString()); nbt.putString("ownerid", playerIn.getUUID().toString()); nbt.putString("entityid", entity_target.getUUID().toString()); itemstack.setTag(nbt); if (UntamedWilds.DEBUG) { UntamedWilds.LOGGER.log(Level.INFO, "Pet owner signed a deed for a " + entity_target.getName().getString()); } event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS); } else { if (itemstack.getTag() != null) { if (entity_target.getOwnerUUID().toString().equals(itemstack.getTag().getString("ownerid")) && entity_target.getUUID().toString().equals(itemstack.getTag().getString("entityid"))) { entity_target.setOwnerUUID(playerIn.getUUID()); if (!playerIn.isCreative()) { itemstack.shrink(1); } if (UntamedWilds.DEBUG) { UntamedWilds.LOGGER.log(Level.INFO, "Pet ownership transferred to " + playerIn.getName().getString()); } } event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS); } } } } event.setCancellationResult(InteractionResult.PASS); } } }
3,413
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ModCreativeModeTab.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/ModCreativeModeTab.java
package untamedwilds.util; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import untamedwilds.init.ModItems; import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class ModCreativeModeTab extends CreativeModeTab { public static final ModCreativeModeTab untamedwilds_items = new ModCreativeModeTab(ModCreativeModeTab.TABS.length, "untamedwilds_items"); private ModCreativeModeTab(int index, String label) { super(index, label); } @Override public ItemStack makeIcon() { return new ItemStack(ModItems.LOGO.get()); } }
729
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SpawnDataHolder.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/SpawnDataHolder.java
package untamedwilds.util; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.biome.Biome; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMobTerrestrial; import untamedwilds.world.FaunaHandler; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class SpawnDataHolder { // Negative numbers are used to signify when to use the EntityDataHolder value instead public static final Codec<SpawnDataHolder> CODEC = RecordCodecBuilder.create((p_237051_0_) -> p_237051_0_.group( Codec.STRING.fieldOf("name").orElse("").forGetter((p_237056_0_) -> p_237056_0_.name), FaunaHandler.SpawnListEntry.CODEC.listOf().fieldOf("entries").orElse(Collections.emptyList()).forGetter((p_237054_0_) -> p_237054_0_.entries)) .apply(p_237051_0_, SpawnDataHolder::new)); private final String name; private final List<FaunaHandler.SpawnListEntry> entries; public SpawnDataHolder(String p_i232114_1_, List<FaunaHandler.SpawnListEntry> entriesIn) { this.name = p_i232114_1_; this.entries = entriesIn; if (FaunaHandler.getSpawnableList(p_i232114_1_) != null) { FaunaHandler.getSpawnableList(p_i232114_1_).addAll(entriesIn); } } public List<FaunaHandler.SpawnListEntry> getEntries () { return this.entries; } }
1,717
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EntityDataHolder.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/EntityDataHolder.java
package untamedwilds.util; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMobTerrestrial; import javax.annotation.Nullable; import java.util.*; public class EntityDataHolder { public static final Codec<EntityDataHolder> CODEC = RecordCodecBuilder.create((p_237051_0_) -> p_237051_0_.group( Codec.STRING.fieldOf("name").orElse("").forGetter((p_237056_0_) -> p_237056_0_.name), Codec.FLOAT.fieldOf("scale").orElse(1F).forGetter((p_237055_0_) -> p_237055_0_.modelScale), Codec.INT.fieldOf("rarity").orElse(0).forGetter((p_237054_0_) -> p_237054_0_.rarity), Codec.FLOAT.fieldOf("attack").orElse(-1F).forGetter((p_237054_0_) -> p_237054_0_.attack), Codec.FLOAT.fieldOf("health").orElse(-1F).forGetter((p_237054_0_) -> p_237054_0_.health), ComplexMobTerrestrial.ActivityType.CODEC.fieldOf("activityType").orElse(ComplexMobTerrestrial.ActivityType.INSOMNIAC).forGetter((p_237052_0_) -> p_237052_0_.activityType), Codec.STRING.fieldOf("favourite_food").orElse("").forGetter((p_237052_0_) -> p_237052_0_.favouriteFood_input), Codec.INT.fieldOf("growing_time").orElse(1).forGetter((p_237054_0_) -> p_237054_0_.growing_time), Codec.INT.fieldOf("offspring").orElse(1).forGetter((p_237054_0_) -> p_237054_0_.offspring), Codec.STRING.fieldOf("breeding_season").orElse("ANY").forGetter((p_237054_0_) -> p_237054_0_.breeding_season), //Codec.unboundedMap(Codec.STRING, SoundEvent.CODEC).fieldOf("sounds").orElse(Collections.emptyMap()).forGetter((p_237052_0_) -> p_237052_0_.sounds), Codec.unboundedMap(Codec.STRING, SoundEvent.CODEC).fieldOf("sounds").orElse(Collections.emptyMap()).forGetter((p_237052_0_) -> p_237052_0_.sounds), Codec.unboundedMap(Codec.STRING, Codec.INT).fieldOf("flags").orElse(Collections.emptyMap()).forGetter((p_237054_0_) -> p_237054_0_.flags), SpeciesDataHolder.CODEC.listOf().fieldOf("species").orElse(new ArrayList<>()).forGetter((p_237052_0_) -> p_237052_0_.speciesData)) .apply(p_237051_0_, EntityDataHolder::new)); private final String name; private final float modelScale; private final int rarity; private final float attack; private final float health; private final ComplexMobTerrestrial.ActivityType activityType; private final String favouriteFood_input; private final ItemStack favouriteFood; private final int growing_time; private final int offspring; private final String breeding_season; public final Map<String, SoundEvent> sounds; private final Map<String, Integer> flags; private final List<SpeciesDataHolder> speciesData; public EntityDataHolder(String p_i232114_1_, float p_i232114_2_, int p_i232114_3_, float attack, float health, ComplexMobTerrestrial.ActivityType activityType, String favouriteFood, int growing_time, int offspring, String breeding, Map<String, SoundEvent> sounds, Map<String, Integer> flags, List<SpeciesDataHolder> speciesData) { this.name = p_i232114_1_; this.modelScale = p_i232114_2_; this.rarity = p_i232114_3_; this.attack = attack; this.health = health; this.activityType = activityType; this.favouriteFood_input = favouriteFood; this.favouriteFood = new ItemStack(ForgeRegistries.ITEMS.getValue(ResourceLocation.tryParse(this.favouriteFood_input))); this.growing_time = growing_time; this.offspring = offspring; this.breeding_season = breeding; // ambient: Ambient sound, hurt: Hurt sound, death: Death sound, threat: Threat sound this.sounds = sounds; // Additional data I can't be arsed to properly define, due to it being specific for each class this.flags = flags; this.speciesData = speciesData; } public String getString() { return this.name + ": Scale: " + this.modelScale + " Rarity: " + this.rarity + " Attack: " + this.attack + " Health: " + this.health + " Ambient Sound: " + this.sounds; } public void printSpeciesData() { for (SpeciesDataHolder speciesDatum : this.speciesData) { UntamedWilds.LOGGER.info(speciesDatum.getString()); } } public String getName(int i) { if (Objects.equals(this.speciesData.get(i).getName(), "")) { return this.name; } return this.speciesData.get(i).getName(); } public float getScale(int i) { if (this.speciesData.get(i).getModelScale() < 0) { return this.modelScale; } return this.speciesData.get(i).getModelScale(); } public int getRarity(int i) { if (this.speciesData.get(i).getRarity() < 0) { return this.rarity; } return this.speciesData.get(i).getRarity(); } public float getAttack(int i) { if (this.speciesData.get(i).getAttack() < 0) { return this.modelScale; } return this.speciesData.get(i).getAttack(); } public float getHealth(int i) { if (this.speciesData.get(i).getHealth() < 0) { return this.modelScale; } return this.speciesData.get(i).getHealth(); } public ComplexMobTerrestrial.ActivityType getActivityType(int i) { if (this.speciesData.get(i).getActivityType() == ComplexMobTerrestrial.ActivityType.INSOMNIAC) { return this.activityType; } return this.speciesData.get(i).getActivityType(); } public ItemStack getFavouriteFood(int i) { if (this.speciesData.get(i).getFavouriteFood().getItem().getRegistryName().toString().equals("minecraft:air")) { return this.favouriteFood; } return this.speciesData.get(i).getFavouriteFood(); } public int getGrowingTime(int i) { if (this.speciesData.get(i).getGrowingTime() < 0) { return this.growing_time; } return this.speciesData.get(i).getGrowingTime(); } public int getOffspring(int i) { if (this.speciesData.get(i).getOffspring() < 0) { return this.offspring; } return this.speciesData.get(i).getOffspring(); } public Integer getSkins(int i) { return this.speciesData.get(i).getSkins(); } public String getBreedingSeason(int i) { if (this.speciesData.get(i).getBreedingSeason().equals("NONE")) { return this.breeding_season; } return this.speciesData.get(i).getBreedingSeason(); } @Nullable public SoundEvent getSoundsWithAlt(int i, String sound_id, SoundEvent alt_sound) { SoundEvent event = this.getSounds(i, sound_id); if (event == null) return alt_sound; return event; } @Nullable public SoundEvent getSounds(int i, String sound_id) { if (!this.speciesData.get(i).getSounds().isEmpty() && this.speciesData.get(i).getSounds().get(sound_id) != null) { return this.speciesData.get(i).getSounds().get(sound_id); } return this.sounds.get(sound_id); } public Map<String, SoundEvent> getBaseSounds() { return this.sounds; } public Integer getGroupCount(int i) { if (!this.speciesData.get(i).getFlags().isEmpty() && this.speciesData.get(i).getFlags().get("groupCount") != null) { return this.speciesData.get(i).getFlags().get("groupCount"); } return 1; } @Nullable public int getFlags(int i, String flag) { if (!this.speciesData.get(i).getFlags().isEmpty() && this.speciesData.get(i).getFlags().get(flag) != null) { return this.speciesData.get(i).getFlags().get(flag); } if (!this.flags.containsKey(flag)) { UntamedWilds.LOGGER.error("Couldn't find " + flag + " flag in ENTITY_DATA"); return 0; } return this.flags.get(flag); } public List<SpeciesDataHolder> getSpeciesData() { return this.speciesData; } }
8,383
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EntityDataHolderClient.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/EntityDataHolderClient.java
package untamedwilds.util; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import java.util.HashMap; import java.util.Map; public class EntityDataHolderClient { public final Map<Integer, Map<String, SoundEvent>> sounds; public final HashMap<Integer, String> species_data; public EntityDataHolderClient(Map<Integer, Map<String, SoundEvent>> p_i232114_3_, HashMap<Integer, String> attack) { this.sounds = p_i232114_3_; this.species_data = attack; } /*@Nullable public SoundEvent getSoundsWithAlt(int i, String sound_id, SoundEvent alt_sound) { SoundEvent event = this.getSounds(i, sound_id); if (event == null) return alt_sound; return event; } @Nullable public SoundEvent getSounds(int i, String sound_id) { UntamedWilds.LOGGER.info(this.sounds.toString()); if (this.sounds.containsKey(i) && this.sounds.get(i).containsKey(sound_id)) { return this.sounds.get(i).get(sound_id); } if (this.sounds.get(-1).containsKey(sound_id)) { return this.sounds.get(-1).get(sound_id); } return null; }*/ public String getSpeciesName(int i) { return this.species_data.get(i); } public int getNumberOfSpecies() { return this.species_data.size(); } public void addSpeciesName(int id, String name) { if (!this.species_data.containsKey(id)) { this.species_data.put(id, name); } } public void addSoundData(int id, String sound_type, ResourceLocation sound) { if (!this.sounds.containsKey(id)) { this.sounds.put(id, new HashMap<>()); } this.sounds.get(id).put(sound_type, new SoundEvent(sound)); } /*@Nullable public SoundEvent getSound(int id, String sound_type) { UntamedWilds.LOGGER.info(this.sounds.toString()); if (this.sounds.containsKey(id) && this.sounds.get(id).containsKey(sound_type)) { return this.sounds.get(id).get(sound_type); } if (this.sounds.containsKey(-1) && this.sounds.get(-1).containsKey(sound_type)) { return this.sounds.get(-1).get(sound_type); } return null; }*/ }
2,280
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SpeciesDataHolder.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/SpeciesDataHolder.java
package untamedwilds.util; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.Holder; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.biome.Biome; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMobTerrestrial; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class SpeciesDataHolder { // Negative numbers are used to signify when to use the EntityDataHolder value instead public static final Codec<SpeciesDataHolder> CODEC = RecordCodecBuilder.create((p_237051_0_) -> p_237051_0_.group( Codec.STRING.fieldOf("name").orElse("").forGetter((p_237056_0_) -> p_237056_0_.name), Codec.INT.fieldOf("variant").orElse(0).forGetter((p_237054_0_) -> p_237054_0_.variant), Codec.FLOAT.fieldOf("scale").orElse(-1F).forGetter((p_237055_0_) -> p_237055_0_.modelScale), Codec.INT.fieldOf("rarity").orElse(-1).forGetter((p_237054_0_) -> p_237054_0_.rarity), Codec.FLOAT.fieldOf("attack").orElse(-1F).forGetter((p_237055_0_) -> p_237055_0_.attack), Codec.FLOAT.fieldOf("health").orElse(-1F).forGetter((p_237055_0_) -> p_237055_0_.health), ComplexMobTerrestrial.ActivityType.CODEC.fieldOf("activityType").orElse(ComplexMobTerrestrial.ActivityType.INSOMNIAC).forGetter((p_237052_0_) -> p_237052_0_.activityType), Codec.STRING.fieldOf("favourite_food").orElse("").forGetter((p_237052_0_) -> p_237052_0_.favouriteFood_input), Codec.INT.fieldOf("growing_time").orElse(-1).forGetter((p_237054_0_) -> p_237054_0_.growing_time), Codec.INT.fieldOf("offspring").orElse(-1).forGetter((p_237054_0_) -> p_237054_0_.offspring), Codec.INT.fieldOf("skins").orElse(10).forGetter((p_237054_0_) -> p_237054_0_.skins), //Codec.pair(Codec.INT, Codec.INT).fieldOf("skins").orElse(new Pair<>(1, 0)).forGetter((p_237054_0_) -> p_237054_0_.skins), Codec.STRING.fieldOf("breeding_season").orElse("NONE").forGetter((p_237054_0_) -> p_237054_0_.breeding_season), Codec.unboundedMap(Codec.STRING, SoundEvent.CODEC).fieldOf("sounds").orElse(Collections.emptyMap()).forGetter((p_237052_0_) -> p_237052_0_.sounds), Codec.unboundedMap(Codec.STRING, Codec.INT).fieldOf("flags").orElse(Collections.emptyMap()).forGetter((p_237054_0_) -> p_237054_0_.flags), Codec.STRING.listOf().listOf().fieldOf("spawnBiomes").orElse(new ArrayList<>()).forGetter((p_237052_0_) -> p_237052_0_.spawnBiomes)) .apply(p_237051_0_, SpeciesDataHolder::new)); private final String name; private final int variant; private final Float modelScale; private final int rarity; private final float attack; private final float health; private final ComplexMobTerrestrial.ActivityType activityType; private final String favouriteFood_input; private final ItemStack favouriteFood; private final int growing_time; private final int offspring; private final int skins; private final String breeding_season; private final Map<String, SoundEvent> sounds; private final Map<String, Integer> flags; private final List<List<String>> spawnBiomes; private final List<List<BiomeTestHolder>> spawnBiomeData; public SpeciesDataHolder(String p_i232114_1_, int variant, float p_i232114_2_, int p_i232114_3_, float attack, float health, ComplexMobTerrestrial.ActivityType activityType, String favourite_food, int growing_time, int offspring, int skins, String breeding_season, Map<String, SoundEvent> sounds, Map<String, Integer> flags, List<List<String>> spawn_biomes) { this.name = p_i232114_1_; this.variant = variant; this.modelScale = p_i232114_2_; this.rarity = p_i232114_3_; this.attack = attack; this.health = health; this.activityType = activityType; this.favouriteFood_input = favourite_food; this.favouriteFood = new ItemStack(ForgeRegistries.ITEMS.getValue(ResourceLocation.tryParse(this.favouriteFood_input))); this.growing_time = growing_time; this.offspring = offspring; this.skins = skins; this.breeding_season = breeding_season; this.sounds = sounds; this.flags = flags; this.spawnBiomes = spawn_biomes; this.spawnBiomeData = new ArrayList<>(); for (List<String> sublist : this.spawnBiomes) { List<BiomeTestHolder> subsublist = new ArrayList<>(); for (String condition : sublist) { String key = condition; if (condition.contains("|")) key = condition.split("\\|")[1]; ConditionTypes type = getTypeOfCondition(condition); ConditionModifiers modifier = getModifierFromString(condition); BiomeTestHolder testHolder = new BiomeTestHolder(key, type, modifier); if (UntamedWilds.DEBUG) { UntamedWilds.LOGGER.info("Registering new" + modifier.getString() + "BiomeTestHolder from " + key + " with type " + type.getString()); } subsublist.add(testHolder); } this.spawnBiomeData.add(subsublist); } } public String getString() { return this.name + ": Scale: " + this.modelScale + " Rarity: " + this.rarity + " Spawn Biomes: " + this.spawnBiomes; } public String getName() { return this.name; } public int getVariant() { return this.variant; } public Float getModelScale() { return this.modelScale; } public Integer getRarity() { return this.rarity; } public Float getAttack() { return this.attack; } public Float getHealth() { return this.health; } public ComplexMobTerrestrial.ActivityType getActivityType() { return this.activityType; } @Nullable public ItemStack getFavouriteFood() { return this.favouriteFood; } public Integer getGrowingTime() { return this.growing_time; } public Integer getOffspring() { return this.offspring; } public Integer getSkins() { return this.skins; } public String getBreedingSeason() { return this.breeding_season; } public Map<String, SoundEvent> getSounds() { return this.sounds; } public Map<String, Integer> getFlags() { return this.flags; } public List<List<BiomeTestHolder>> getBiomeCategories() { return this.spawnBiomeData; } public static ConditionModifiers getModifierFromString(String strIn) { if (strIn.contains("!")) return ConditionModifiers.INVERTED; else if (strIn.contains("#")) return ConditionModifiers.PRIORITY; return ConditionModifiers.NONE; } public static ConditionTypes getTypeOfCondition(String strIn) { String clean = strIn.replaceAll("[!#]",""); if (clean.contains("|")) { String str = clean.split("\\|")[0]; switch (str) { case "category": return ConditionTypes.BIOME_CATEGORY; case "dictionary": return ConditionTypes.FORGE_DICTIONARY; case "tag": return ConditionTypes.BIOME_TAG; case "resource": return ConditionTypes.REGISTRY_NAME; } } return ConditionTypes.BIOME_CATEGORY; } public enum ConditionTypes { BIOME_CATEGORY ("Category"), FORGE_DICTIONARY ("Dictionary"), BIOME_TAG ("Tag"), REGISTRY_NAME ("Resource Location"); public String type; ConditionTypes(String type) { this.type = type; } public String getString() { return this.type; } } public enum ConditionModifiers { NONE (" "), INVERTED (" Inverted "), PRIORITY (" Priority "); public String type; ConditionModifiers(String type) { this.type = type; } public String getString() { return this.type; } } public static class BiomeTestHolder { private final String key; private final ConditionTypes type; private final ConditionModifiers modifier; public BiomeTestHolder(String key, ConditionTypes typeIn, ConditionModifiers modifierIn) { this.key = key; this.type = typeIn; this.modifier = modifierIn; } public boolean isValidBiome(Holder<Biome> biomekey, Biome biome) { boolean result = switch (this.type) { case BIOME_CATEGORY -> biome.biomeCategory == Biome.BiomeCategory.byName(this.key); case FORGE_DICTIONARY -> BiomeDictionary.hasType(biomekey.unwrapKey().get(), BiomeDictionary.Type.getType(this.key)); case BIOME_TAG -> biomekey.is(new ResourceLocation(this.key)); case REGISTRY_NAME -> biome.getRegistryName().equals(new ResourceLocation(this.key)); }; if (this.modifier == ConditionModifiers.INVERTED) { return !result; } return result; } } }
9,765
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EntityDataListenerEvent.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/EntityDataListenerEvent.java
package untamedwilds.util; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import untamedwilds.UntamedWilds; import untamedwilds.entity.ComplexMob; import untamedwilds.init.ModEntity; import untamedwilds.network.SyncTextureData; import untamedwilds.network.UntamedInstance; import java.util.HashMap; import java.util.Objects; @Mod.EventBusSubscriber(modid = UntamedWilds.MOD_ID) public class EntityDataListenerEvent { public static final JSONLoader<EntityDataHolder> ENTITY_DATA_HOLDERS = new JSONLoader<>("entities", EntityDataHolder.CODEC); public static EntityDataHolder TARANTULA; public static EntityDataHolder KING_CRAB; public static EntityDataHolder GIANT_CLAM; public static EntityDataHolder GIANT_SALAMANDER; public static EntityDataHolder NEWT; public static EntityDataHolder AROWANA; public static EntityDataHolder FOOTBALL_FISH; public static EntityDataHolder SHARK; public static EntityDataHolder SUNFISH; public static EntityDataHolder WHALE_SHARK; public static EntityDataHolder TREVALLY; public static EntityDataHolder TRIGGERFISH; public static EntityDataHolder CATFISH; public static EntityDataHolder SPADEFISH; public static EntityDataHolder SNAKE; public static EntityDataHolder ANACONDA; public static EntityDataHolder SOFTSHELL_TURTLE; public static EntityDataHolder TORTOISE; public static EntityDataHolder MONITOR; public static EntityDataHolder AARDVARK; public static EntityDataHolder HIPPO; public static EntityDataHolder RHINO; public static EntityDataHolder HYENA; public static EntityDataHolder BOAR; public static EntityDataHolder BEAR; public static EntityDataHolder BIG_CAT; public static EntityDataHolder BISON; public static EntityDataHolder CAMEL; public static EntityDataHolder MANATEE; public static EntityDataHolder BALEEN_WHALE; public static EntityDataHolder OPOSSUM; public static EntityDataHolder SPITTER; @SubscribeEvent public static void onAddReloadListeners(AddReloadListenerEvent event) { event.addListener(ENTITY_DATA_HOLDERS); registerData(); } private static void registerData() { TARANTULA = registerEntityData(ModEntity.TARANTULA.get()); KING_CRAB = registerEntityData(ModEntity.KING_CRAB.get()); GIANT_CLAM = registerEntityData(ModEntity.GIANT_CLAM.get()); GIANT_SALAMANDER = registerEntityData(ModEntity.GIANT_SALAMANDER.get()); NEWT = registerEntityData(ModEntity.NEWT.get()); AROWANA = registerEntityData(ModEntity.AROWANA.get()); FOOTBALL_FISH = registerEntityData(ModEntity.FOOTBALL_FISH.get()); SHARK = registerEntityData(ModEntity.SHARK.get()); SUNFISH = registerEntityData(ModEntity.SUNFISH.get()); TREVALLY = registerEntityData(ModEntity.TREVALLY.get()); WHALE_SHARK = registerEntityData(ModEntity.WHALE_SHARK.get()); TRIGGERFISH = registerEntityData(ModEntity.TRIGGERFISH.get()); CATFISH = registerEntityData(ModEntity.CATFISH.get()); SPADEFISH = registerEntityData(ModEntity.SPADEFISH.get()); SNAKE = registerEntityData(ModEntity.SNAKE.get()); ANACONDA = registerEntityData(ModEntity.ANACONDA.get()); SOFTSHELL_TURTLE = registerEntityData(ModEntity.SOFTSHELL_TURTLE.get()); TORTOISE = registerEntityData(ModEntity.TORTOISE.get()); MONITOR = registerEntityData(ModEntity.MONITOR.get()); BEAR = registerEntityData(ModEntity.BEAR.get()); BIG_CAT = registerEntityData(ModEntity.BIG_CAT.get()); AARDVARK = registerEntityData(ModEntity.AARDVARK.get()); BOAR = registerEntityData(ModEntity.BOAR.get()); RHINO = registerEntityData(ModEntity.RHINO.get()); HYENA = registerEntityData(ModEntity.HYENA.get()); HIPPO = registerEntityData(ModEntity.HIPPO.get()); BISON = registerEntityData(ModEntity.BISON.get()); CAMEL = registerEntityData(ModEntity.CAMEL.get()); MANATEE = registerEntityData(ModEntity.MANATEE.get()); BALEEN_WHALE = registerEntityData(ModEntity.BALEEN_WHALE.get()); OPOSSUM = registerEntityData(ModEntity.OPOSSUM.get()); SPITTER = registerEntityData(ModEntity.SPITTER.get()); } @SubscribeEvent public static void onPlayerLogIn(PlayerEvent.PlayerLoggedInEvent event) { UntamedWilds.LOGGER.info("Firing player login event"); registerData(); for (EntityType<?> types : ComplexMob.ENTITY_DATA_HASH.keySet()) { ResourceLocation entityName = types.getRegistryName(); int size = 0; for (SpeciesDataHolder speciesData : ComplexMob.ENTITY_DATA_HASH.get(types).getSpeciesData()) { UntamedInstance.sendToClient(new SyncTextureData(entityName, speciesData.getName(), speciesData.getSkins(), size++), (ServerPlayer) event.getPlayer()); } } } public static EntityDataHolder registerEntityData(EntityType<?> typeIn) { String nameIn = Objects.requireNonNull(typeIn.getRegistryName()).getPath(); if (ENTITY_DATA_HOLDERS.getData(new ResourceLocation(UntamedWilds.MOD_ID, nameIn)) != null) { EntityDataHolder data = ENTITY_DATA_HOLDERS.getData(new ResourceLocation(UntamedWilds.MOD_ID, nameIn)); processData(data, typeIn); return data; } return null; } /** * Method that links an EntityType with an EntityDataHolder object, and uses the EntityDataHolder to build a * hash with only Variant data, to be synced and accessed by the client * @param dataIn The EntityDataHolder to introduce in ENTITY_DATA_HASH * @param typeIn The EntityType to be associated with the dataIn object */ private static void processData(EntityDataHolder dataIn, EntityType<?> typeIn) { ComplexMob.ENTITY_DATA_HASH.put(typeIn, dataIn); processSkins(dataIn, typeIn.getRegistryName().getPath()); for (SpeciesDataHolder speciesData : ComplexMob.ENTITY_DATA_HASH.get(typeIn).getSpeciesData()) { if (!ComplexMob.CLIENT_DATA_HASH.containsKey(typeIn)) { ComplexMob.CLIENT_DATA_HASH.put(typeIn, new EntityDataHolderClient(new HashMap<>(), new HashMap<>())); } ComplexMob.CLIENT_DATA_HASH.get(typeIn).species_data.put(speciesData.getVariant(), speciesData.getName()); } } private static void processSkins(EntityDataHolder dataIn, String nameIn) { for (SpeciesDataHolder speciesDatum : dataIn.getSpeciesData()) { EntityUtils.buildSkinArrays(nameIn, speciesDatum.getName().toLowerCase(), dataIn, speciesDatum.getVariant(), ComplexMob.TEXTURES_COMMON, ComplexMob.TEXTURES_RARE); } } }
7,092
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
JSONLoader.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/JSONLoader.java
package untamedwilds.util; /* The MIT License (MIT) Copyright (c) 2020 Joseph Bettendorff a.k.a. "Commoble" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import com.google.gson.Gson; import com.google.gson.JsonElement; import com.mojang.serialization.Codec; import com.mojang.serialization.JsonOps; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; import net.minecraft.util.profiling.ProfilerFiller; import untamedwilds.UntamedWilds; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class JSONLoader<T> extends SimpleJsonResourceReloadListener { private static final Gson STANDARD_GSON = new Gson(); private final Codec<T> codec; private final String folderName; protected Map<ResourceLocation, T> data = new HashMap<>(); /** * Creates a data manager with a standard gson parser * @param folderName The name of the data folder that we will load from, vanilla folderNames are "recipes", "loot_tables", etc</br> * Jsons will be read from data/all_modids/folderName/all_jsons</br> * folderName can include subfolders, e.g. "some_mod_that_adds_lots_of_data_loaders/cheeses" * @param codec A codec to deserialize the json into your T, see javadocs above class */ public JSONLoader(String folderName, Codec<T> codec) { this(folderName, codec, STANDARD_GSON); } /** * As above but with a custom GSON * @param folderName The name of the data folder that we will load from, vanilla folderNames are "recipes", "loot_tables", etc</br> * Jsons will be read from data/all_modids/folderName/all_jsons</br> * folderName can include subfolders, e.g. "some_mod_that_adds_lots_of_data_loaders/cheeses" * @param codec A codec to deserialize the json into your T, see javadocs above class * @param gson A gson for parsing the raw json data into JsonElements. JsonElement-to-T conversion will be done by the codec, * so gson type adapters shouldn't be necessary here */ public JSONLoader(String folderName, Codec<T> codec, Gson gson) { super(gson, folderName); this.folderName = folderName; this.codec = codec; } /** * Get the data object for the given key * @param id A resourcelocation identifying a json; e.g. a json at data/some_modid/folderName/some_json.json has id "some_modid:some_json" * @return The java object that was deserializd from the json with the given ID, or null if no such object is associated with that ID */ @Nullable public T getData(ResourceLocation id) { return this.data.get(id); } @Override protected void apply(Map<ResourceLocation, JsonElement> jsons, ResourceManager resourceManager, ProfilerFiller profiler) { UntamedWilds.LOGGER.info("Beginning loading of data for data loader: {}", this.folderName); this.data = this.mapValues(jsons); UntamedWilds.LOGGER.info("Data loader for {} loaded {} jsons", this.folderName, this.data.size()); } private Map<ResourceLocation, T> mapValues(Map<ResourceLocation, JsonElement> inputs) { Map<ResourceLocation, T> newMap = new HashMap<>(); for (Entry<ResourceLocation, JsonElement> entry : inputs.entrySet()) { ResourceLocation key = entry.getKey(); JsonElement element = entry.getValue(); // if we fail to parse json, log an error and continue // if we succeeded, add the resulting T to the map this.codec.decode(JsonOps.INSTANCE, element) .get() .ifLeft(result -> newMap.put(key, result.getFirst())) .ifRight(partial -> UntamedWilds.LOGGER.error("Failed to parse data json for {} due to: {}", key.toString(), partial.message())); } return newMap; } }
4,986
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
SpawnDataListenerEvent.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/SpawnDataListenerEvent.java
package untamedwilds.util; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import untamedwilds.UntamedWilds; import untamedwilds.world.FaunaHandler; import java.util.List; @Mod.EventBusSubscriber(modid = UntamedWilds.MOD_ID) public class SpawnDataListenerEvent { public static final JSONLoader<SpawnDataHolder> SPAWN_DATA_HOLDER = new JSONLoader<>("spawn_tables", SpawnDataHolder.CODEC); public static SpawnDataHolder CRITTER; public static SpawnDataHolder HERBIVORES; public static SpawnDataHolder PREDATORS; public static SpawnDataHolder BENTHOS; public static SpawnDataHolder WATER_OCEAN; public static SpawnDataHolder WATER_RIVER; public static SpawnDataHolder UNDERGROUND; @SubscribeEvent public static void onAddReloadListeners(AddReloadListenerEvent event) { event.addListener(SPAWN_DATA_HOLDER); registerData(); } private static void registerData() { CRITTER = registerSpawnData("critter"); HERBIVORES = registerSpawnData("herbivores"); PREDATORS = registerSpawnData("predators"); BENTHOS = registerSpawnData("benthos"); WATER_OCEAN = registerSpawnData("water_ocean"); WATER_RIVER = registerSpawnData("water_river"); UNDERGROUND = registerSpawnData("underground"); } public static SpawnDataHolder registerSpawnData(String nameIn) { if (SPAWN_DATA_HOLDER.getData(new ResourceLocation(UntamedWilds.MOD_ID, nameIn)) != null) { SpawnDataHolder data = SPAWN_DATA_HOLDER.getData(new ResourceLocation(UntamedWilds.MOD_ID, nameIn)); if (FaunaHandler.getSpawnableList(nameIn) != null) { List<FaunaHandler.SpawnListEntry> spawn_list = FaunaHandler.getSpawnableList(nameIn); if (!spawn_list.isEmpty()) spawn_list.addAll(data.getEntries()); return data; } } return null; } }
2,098
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
TimeUtils.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/TimeUtils.java
package untamedwilds.util; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.level.Level; // A set of functions relating Time conversion between Ticks, Days and Months // Handles compatibility with SereneSeasons, using their functions if the Mod and the option are enabled public abstract class TimeUtils { public static String convertTicksToDays(Level world, int ticks) { /*if (CompatBridge.SereneSeasons) { int d = ticks/CompatSereneSeasons.getDayLength(world); if (d > CompatSereneSeasons.getDaysInMonth(world)) { int m = d/CompatSereneSeasons.getDaysInMonth(world); d -= m * CompatSereneSeasons.getDaysInMonth(world); return m + " months and " + d + " days"; } return d + " days"; }*/ int d = ticks/24000; if (d > 7) { int m = d/7; d -= m * 7; return new TranslatableComponent("untamedwilds.timeutils.weeks", m, d).getString(); } return new TranslatableComponent("untamedwilds.timeutils.days", d).getString(); } // No concept of month outside of Serene Seasons public static int getTicksInMonth(Level world) { /*if (CompatBridge.SereneSeasons) { return CompatSereneSeasons.getTicksInMonth(world); }*/ return 168000; } }
1,398
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EntityUtils.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/util/EntityUtils.java
package untamedwilds.util; import com.google.common.collect.Lists; import com.mojang.datafixers.util.Pair; import net.minecraft.ChatFormatting; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TextComponent; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.*; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet; import net.minecraft.world.phys.Vec3; import net.minecraftforge.entity.PartEntity; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigGamerules; import untamedwilds.entity.*; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; // A series of functions that are not meant to be limited to ComplexMobs public abstract class EntityUtils { // Destroy the boat of the selected entity (if it exists) public static void destroyBoat(Level worldIn, LivingEntity entityIn) { if (entityIn.getVehicle() != null && entityIn.getVehicle() instanceof Boat boat) { boat.remove(Entity.RemovalReason.KILLED); if (worldIn.getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT)) { for(int j = 0; j < 3; ++j) boat.spawnAtLocation(boat.getBoatType().getPlanks()); for(int k = 0; k < 2; ++k) boat.spawnAtLocation(Items.STICK); } } } // Spawn particles throughout the entity public static <T extends ParticleOptions> void spawnParticlesOnEntity(Level worldIn, LivingEntity entityIn, T particle, int count, int iter) { if (worldIn.isClientSide) return; if (entityIn.isMultipartEntity()) { for (PartEntity<?> part : entityIn.getParts()) { for (int i = 0; i < iter; i++) { ((ServerLevel)worldIn).sendParticles(particle, part.getX(), part.getY() + (double)part.getBbHeight() / 1.5D, part.getZ(), count, part.getBbWidth() / 4.0F, part.getBbHeight() / 4.0F, part.getBbWidth() / 4.0F, 0.05D); } } } else { for (int i = 0; i < iter; i++) { ((ServerLevel)worldIn).sendParticles(particle, entityIn.getX(), entityIn.getY() + (double)entityIn.getBbHeight() / 1.5D, entityIn.getZ(), count, entityIn.getBbWidth() / 4.0F, entityIn.getBbHeight() / 4.0F, entityIn.getBbWidth() / 4.0F, 0.05D); } } } public static int getPackSize(EntityType<?> type, int variant) { return ComplexMob.getEntityData(type).getGroupCount(variant); } /** * Method to calculate the Blockpos relative to a mob's facing direction, returns a BlockPos * @param entityIn The entity whose facing direction will be used * @param xzOffset Offset in the X and Z axis * @param yOffset Offset in the Y axis */ public static BlockPos getRelativeBlockPos(Entity entityIn, float xzOffset, float yOffset) { return entityIn.blockPosition().offset(Math.cos(Math.toRadians(entityIn.getYRot() + 90)) * xzOffset, yOffset, Math.sin(Math.toRadians(entityIn.getYRot() + 90)) * xzOffset); } // Self-explanatory public static EntityType<?> getEntityTypeFromTag(CompoundTag nbt, @Nullable EntityType<?> alt) { if (nbt != null && nbt.contains("EntityTag", 10)) { CompoundTag entityNBT = nbt.getCompound("EntityTag"); if (entityNBT.contains("id", 8)) { return EntityType.byString(entityNBT.getString("id")).orElse(alt); } } return alt; } // This function builds a full tooltip containing Custom Name, EntityType, Gender and Scientific name (if available) public static void buildTooltipData(ItemStack stack, List<Component> tooltip, EntityType<?> entity, String path) { if (stack.getTag() != null && stack.getTag().contains("EntityTag")) { CompoundTag compound = stack.getTagElement("EntityTag"); //String component = "mobspawn.tooltip." + (compound.contains("Gender") ? (compound.getInt("Gender") == 0 ? "male" : "female") : "unknown"); //tooltip.add(new TranslatableComponent(component).mergeStyle(TextFormatting.GRAY)); String gender = compound.contains("Gender") ? new TranslatableComponent("mobspawn.tooltip." + (compound.getInt("Gender") == 0 ? "male" : "female")).getString() + " " : ""; String type; if (path.isEmpty()) type = new TranslatableComponent(entity.getDescriptionId()).getString(); else type = new TranslatableComponent(entity.getDescriptionId() + "_" + path).getString(); if (stack.getTag().getCompound("EntityTag").contains("CustomName")) { String customName = stack.getTag().getCompound("EntityTag").getString("CustomName"); // Entity uses ITextComponent.Serializer.getComponentFromJson(s) instead of substrings tooltip.add(new TextComponent(customName.substring(9, customName.length() - 2) + " (" + gender + type + ")").withStyle(ChatFormatting.GRAY)); } else { tooltip.add(new TextComponent(gender + type).withStyle(ChatFormatting.GRAY)); } } if (ConfigGamerules.scientificNames.get()) { String scipath = path.isEmpty() ? "" : "_" + path; TranslatableComponent tooltipText = new TranslatableComponent(entity.getDescriptionId() + scipath + ".sciname"); if (!tooltipText.getString().contains(".")) { tooltip.add(tooltipText.withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY)); } } } public static void createMobFromItem(ServerLevel worldIn, ItemStack itemstack, EntityType<?> entity, @Nullable Integer species, BlockPos spawnPos, @Nullable Player player, boolean offset) { createMobFromItem(worldIn, itemstack, entity, species, spawnPos, player, offset, false); } // This function creates a new mob from the NBT Tag stored in an ItemStack. Uses default EntityType and Species data to allow creating new entities from zero public static void createMobFromItem(ServerLevel worldIn, ItemStack itemstack, EntityType<?> entity, @Nullable Integer species, BlockPos spawnPos, @Nullable Player player, boolean offset, boolean skipNBTCheck) { Entity spawn; if (itemstack.getTag() != null) { //UntamedWilds.LOGGER.info(itemstack.getTag().toString()); if (itemstack.getTag().contains("EntityTag") && !skipNBTCheck) { if (itemstack.getTagElement("EntityTag").contains("UUID")) { if (worldIn.getEntity(itemstack.getTagElement("EntityTag").getUUID("UUID")) != null) { itemstack.getTagElement("EntityTag").putUUID("UUID", Mth.createInsecureUUID(worldIn.random)); } } spawn = entity.spawn(worldIn, itemstack, player, spawnPos, MobSpawnType.BUCKET, true, offset); if (spawn != null && itemstack.hasCustomHoverName()) { spawn.setCustomName(itemstack.getHoverName()); } } else { // If no NBT data is assigned to the entity (eg. Item taken from the Creative menu), create a new, random mob spawn = entity.create(worldIn, null, null, player, spawnPos, MobSpawnType.SPAWN_EGG, true, offset); if (spawn instanceof ComplexMob entitySpawn) { int true_species = species != null ? species : entitySpawn.getRandom().nextInt(ComplexMob.getEntityData(entitySpawn.getType()).getSpeciesData().size()); entitySpawn.setVariant(true_species); entitySpawn.chooseSkinForSpecies(entitySpawn, true); entitySpawn.setRandomMobSize(); entitySpawn.setGender(entitySpawn.getRandom().nextInt(2)); if (spawn instanceof INeedsPostUpdate) ((INeedsPostUpdate) spawn).updateAttributes(); } if (spawn != null) { if (itemstack.hasCustomHoverName()) { spawn.setCustomName(itemstack.getHoverName()); } worldIn.addFreshEntityWithPassengers(spawn); } } } } // This function makes the entity drop some Eggs of the given item_name, and with random stacksize between 1 and number public static void dropEggs(ComplexMob entity, String item_name, int number) { if (ConfigGamerules.mobsLayEggs.get()) { CompoundTag baseTag = new CompoundTag(); ItemStack item = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(UntamedWilds.MOD_ID + ":" + item_name.toLowerCase()))); baseTag.putInt("variant", entity.getVariant()); baseTag.putInt("custom_model_data", entity.getVariant()); item.setTag(baseTag); ItemEntity entityitem = entity.spawnAtLocation(item, 0.2F); if (entityitem != null) { entityitem.getItem().setCount(1 + entity.getRandom().nextInt(number - 1)); } } } // This function turns the entity into an item with item_name registry name, and removes the entity from the world public static void turnEntityIntoItem(LivingEntity entity, String item_name) { if (ConfigGamerules.easyMobCapturing.get() || ((Mob)entity).getTarget() == null) { ItemEntity entityitem = entity.spawnAtLocation(new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(UntamedWilds.MOD_ID + ":" + item_name.toLowerCase()))), 0.2F); Random rand = entity.getRandom(); if (entityitem != null) { entityitem.setDeltaMovement((rand.nextFloat() - rand.nextFloat()) * 0.1F, rand.nextFloat() * 0.05F, (rand.nextFloat() - rand.nextFloat()) * 0.1F); entityitem.getItem().setTag(writeEntityToNBT(entity, false, true)); if (entity.hasCustomName()) { entityitem.getItem().setHoverName(entity.getCustomName()); } entity.discard(); } } } // This function replaces a given ItemStack with a new item with item_name registry name, and removes the entity from the world public static void mutateEntityIntoItem(LivingEntity entity, Player player, InteractionHand hand, String item_name, ItemStack itemstack) { if (ConfigGamerules.easyMobCapturing.get() || ((Mob)entity).getTarget() == null) { entity.playSound(SoundEvents.BUCKET_FILL_FISH, 1.0F, 1.0F); itemstack.shrink(1); ItemStack newitem = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(UntamedWilds.MOD_ID + ":" + item_name.toLowerCase()))); newitem.setTag(writeEntityToNBT(entity, false, true)); if (entity.hasCustomName()) { newitem.setHoverName(entity.getCustomName()); } if (!entity.getLevel().isClientSide) { CriteriaTriggers.FILLED_BUCKET.trigger((ServerPlayer) player, newitem); } if (itemstack.isEmpty()) { player.setItemInHand(hand, newitem); } else if (!player.getInventory().add(newitem)) { player.drop(newitem, false); } entity.discard(); } } // This function pulls X items from the defined LootTable public static List<ItemStack> getItemFromLootTable(ResourceLocation lootTableIn, Level worldIn) { LootContext.Builder lootcontext$builder = new LootContext.Builder((ServerLevel) worldIn); if (worldIn.getServer() != null) { return worldIn.getServer().getLootTables().get(lootTableIn).getRandomItems(lootcontext$builder.create(new LootContextParamSet.Builder().build())); } return Lists.newArrayList(); } public static CompoundTag writeEntityToNBT(LivingEntity entity) { return writeEntityToNBT(entity, false); } public static CompoundTag writeEntityToNBT(LivingEntity entity, boolean keepHomeData) { return writeEntityToNBT(entity, keepHomeData, false); } // This method writes this entity into a CompoundTag Tag public static CompoundTag writeEntityToNBT(LivingEntity entity, boolean keepHomeData, boolean attachModelData) { CompoundTag baseTag = new CompoundTag(); CompoundTag entityTag = new CompoundTag(); entity.saveAsPassenger(entityTag); entityTag.remove("Pos"); // Remove the Position from the NBT data, as it would fuck things up later on entityTag.remove("Motion"); if (entityTag.contains("BoundingBox")) { entityTag.remove("BoundingBox"); // Stripping this NBT data prevents RandomPatches from moving mobs back to their original position } if (entityTag.contains("Leash")) { entityTag.remove("Leash"); // Stripping this NBT data prevents Leash duplication from caging/catching Leashed mobs } if (entity instanceof ISpecies && !keepHomeData) { entityTag.remove("HomePosX"); entityTag.remove("HomePosY"); entityTag.remove("HomePosZ"); } if (attachModelData && entity instanceof ComplexMob) { baseTag.putInt("CustomModelData", ((ComplexMob) entity).getVariant()); } baseTag.put("EntityTag", entityTag); // Put the entity in the Tag return baseTag; } // Returns whether an entity has full HP or not (takes into account overloaded HP) public static boolean hasFullHealth(LivingEntity entityIn) { return entityIn.getHealth() >= entityIn.getMaxHealth(); } // Pulls all resources with the given name from the provided ResourceLocation public static Pair<Integer, Integer> buildSkinArrays(String name, String species, EntityDataHolder dataIn, int variant, HashMap<String, HashMap<Integer, ArrayList<ResourceLocation>>> common_list, HashMap<String, HashMap<Integer, ArrayList<ResourceLocation>>> rare_list) { return buildSkinArrays(name, species, dataIn.getSkins(variant), variant, common_list, rare_list); } // Pulls all resources with the given name from the provided ResourceLocation public static Pair<Integer, Integer> buildSkinArrays(String name, String species, int skins, int variant, HashMap<String, HashMap<Integer, ArrayList<ResourceLocation>>> common_list, HashMap<String, HashMap<Integer, ArrayList<ResourceLocation>>> rare_list) { String path = "textures/entity/" + name + "/" + species; if (!common_list.containsKey(name)) { common_list.put(name, new HashMap<>()); } if (!rare_list.containsKey(name)) { rare_list.put(name, new HashMap<>()); } Pair<Integer, Integer> values = new Pair<>((skins / 10) - 1, (skins % 10) - 1); common_list.get(name).put(variant, new ArrayList<>()); if (values.getFirst() >= 1) { for (int i = 0; i <= values.getFirst(); i++) { final String full_path = String.format(path + "_%d.png", i + 1); common_list.get(name).get(variant).add(new ResourceLocation(UntamedWilds.MOD_ID, full_path)); } } else { common_list.get(name).get(variant).add(new ResourceLocation(UntamedWilds.MOD_ID, path + ".png")); } if (values.getSecond() >= 0) { rare_list.get(name).put(variant, new ArrayList<>()); for (int i = 0; i <= values.getSecond(); i++) { final String full_path = String.format(path + "_%dr.png", i + 1); rare_list.get(name).get(variant).add(new ResourceLocation(UntamedWilds.MOD_ID, full_path)); } } //Pair<Integer, Integer> result = new Pair<>(populateSkinArray(path, "_%d.png", variant, common_list.get(name), true), populateSkinArray(path, "_%dr.png", variant, rare_list.get(name), false)); if (UntamedWilds.DEBUG) { UntamedWilds.LOGGER.info("Number of textures for " + species + " " + name + ": " + values); } return values; } // Populates the provided array with the data located in the specified path @Deprecated public static int populateSkinArray(String path, String suffix, int variant, HashMap<Integer, ArrayList<ResourceLocation>> list, boolean addDefault) { list.put(variant, new ArrayList<>()); for (int i = 0; i < 99; i++) { int k = i; try { if (!suffix.matches("[^a-z0-9/._:-]")) { final String full_path = String.format(path + suffix, i + 1); Minecraft.getInstance().getResourceManager().getResource(new ResourceLocation(UntamedWilds.MOD_ID, full_path)); list.get(variant).add(new ResourceLocation(UntamedWilds.MOD_ID, full_path)); } else { UntamedWilds.LOGGER.error("Invalid character in " + suffix + ", terminating Skin registry"); break; } } catch (Exception e) { if (k == 0 && addDefault) { //UntamedWilds.LOGGER.info("Using the default path instead"); list.get(variant).add(new ResourceLocation(UntamedWilds.MOD_ID, path + ".png")); k++; } //UntamedWilds.LOGGER.info(k + " " + variant + " " + path + " " + list); if (list.get(variant).isEmpty()) { list.remove(variant); } return k; } } return 0; } public static String getVariantName(EntityType<?> typeIn, int variantIn) { if (ComplexMob.ENTITY_DATA_HASH.containsKey(typeIn)) { return ComplexMob.ENTITY_DATA_HASH.get(typeIn).getName(variantIn); } else if (ComplexMob.CLIENT_DATA_HASH.containsKey(typeIn)) { return ComplexMob.CLIENT_DATA_HASH.get(typeIn).getSpeciesName(variantIn); } //UntamedWilds.LOGGER.warn("There's no name provided for the species"); return ""; } public static int getNumberOfSpecies(EntityType<?> typeIn) { if (ComplexMob.ENTITY_DATA_HASH.containsKey(typeIn)) { return ComplexMob.ENTITY_DATA_HASH.get(typeIn).getSpeciesData().size(); } else if (ComplexMob.CLIENT_DATA_HASH.containsKey(typeIn)) { return ComplexMob.CLIENT_DATA_HASH.get(typeIn).getNumberOfSpecies(); } UntamedWilds.LOGGER.warn("There's no species provided for the EntityType"); return 0; } public static SoundEvent getSound(EntityType<?> typeIn, int variantIn, String sound_type) { return getSound(typeIn, variantIn, sound_type, null); } public static SoundEvent getSound(EntityType<?> typeIn, int variantIn, String sound_type, @Nullable SoundEvent fallback) { if (ComplexMob.ENTITY_DATA_HASH.containsKey(typeIn)) { SoundEvent location = ComplexMob.ENTITY_DATA_HASH.get(typeIn).getSounds(variantIn, sound_type); if (location != null) { return ForgeRegistries.SOUND_EVENTS.getValue(location.getLocation()); } } /*else if (ComplexMob.CLIENT_DATA_HASH.containsKey(typeIn)) { SoundEvent location = ComplexMob.CLIENT_DATA_HASH.get(typeIn).getSounds(variantIn, sound_type); if (location != null) { return ForgeRegistries.SOUND_EVENTS.getValue(location.name); } }*/ //UntamedWilds.LOGGER.warn("There's no name provided for the species"); return fallback; } public static int getClampedNumberOfSpecies(int i, EntityType<?> typeIn) { int size = Math.max(0, EntityUtils.getNumberOfSpecies(typeIn) - 1); if (i > size) { UntamedWilds.LOGGER.warn("Correcting wrong Variant value of " + i + " to " + size); } return Mth.clamp(i, 0, size); } // Takes the skin from the TEXTURES_COMMON or TEXTURES_RARE array public static ResourceLocation getSkinFromEntity(ComplexMob entityIn) { if (entityIn.getType().getRegistryName() != null) { String name = entityIn.getType().getRegistryName().getPath(); if (entityIn.getSkin() > 99 && ComplexMob.TEXTURES_RARE.get(name).containsKey(entityIn.getVariant())) { return ComplexMob.TEXTURES_RARE.get(name).get(entityIn.getVariant()).get(Math.min(entityIn.getSkin() - 100, ComplexMob.TEXTURES_RARE.get(name).get(entityIn.getVariant()).size() - 1)); } if (entityIn.getVariant() >= 0) return ComplexMob.TEXTURES_COMMON.get(name).get(entityIn.getVariant()).get(Math.min(entityIn.getSkin(), ComplexMob.TEXTURES_COMMON.get(name).get(entityIn.getVariant()).size() - 1)); } //UntamedWilds.LOGGER.warn("No Skin found for entity: " + entityIn.getType().getRegistryName()); return new ResourceLocation("missing"); } // Tests an ItemStack and consumes it if found to be a Food. Also applies it's effects public static void consumeItemStack(TamableAnimal entityIn, ItemStack itemstack) { if (itemstack.isEdible()) { FoodProperties itemFood = itemstack.getItem().getFoodProperties(); if (itemFood != null) { entityIn.playSound(SoundEvents.GENERIC_EAT, 1, 1); if (entityIn instanceof ComplexMobTerrestrial) ((ComplexMobTerrestrial)entityIn).addHunger(itemFood.getNutrition() * 10); else entityIn.heal(itemFood.getNutrition()); for (Pair<MobEffectInstance, Float> pair : itemFood.getEffects()) { if (pair.getFirst() != null && entityIn.level.random.nextFloat() < pair.getSecond()) { entityIn.addEffect(new MobEffectInstance(pair.getFirst())); } } } } else if (!PotionUtils.getMobEffects(itemstack).isEmpty()) { entityIn.playSound(SoundEvents.GENERIC_DRINK, 1, 1); if (entityIn instanceof ComplexMobTerrestrial) ((ComplexMobTerrestrial)entityIn).addHunger(10); for(MobEffectInstance effectinstance : PotionUtils.getMobEffects(itemstack)) { if (effectinstance.getEffect().isInstantenous()) effectinstance.getEffect().applyInstantenousEffect(entityIn.getOwner(), entityIn.getOwner(), entityIn, effectinstance.getAmplifier(), 1.0D); else entityIn.addEffect(new MobEffectInstance(effectinstance)); } } } public static Vec3 getOvershootPath(Entity entityIn, Entity targetIn, double overshoot) { double x = targetIn.getX() - entityIn.getX(); double z = targetIn.getZ() - entityIn.getZ(); float angle = (float) (Math.atan2(z, x)); double dist = Mth.sqrt((float) (Math.pow(x, 2) + Math.pow(z, 2))); double add_x = Mth.cos(angle) * (dist + overshoot); double add_z = Mth.sin(angle) * (dist + overshoot); return new Vec3(entityIn.getX() + add_x, targetIn.getY(), entityIn.getZ() + add_z); } // Checks if a mob is NOT a valid partner for the input. Both entityIn and partnerIn should be the same class public static boolean isInvalidPartner(ComplexMob entityIn, ComplexMob partnerIn, boolean isHermaphrodite) { if (entityIn instanceof INestingMob nesting && (nesting.wantsToLayEggs() || ((INestingMob)partnerIn).wantsToLayEggs())) { return true; } return (ConfigGamerules.genderedBreeding.get() && (partnerIn.getGender() == entityIn.getGender() || isHermaphrodite)) || (partnerIn.getVariant() != entityIn.getVariant()) || partnerIn.getAge() != 0; } }
25,166
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
IPostGenUpdate.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/IPostGenUpdate.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.world.level.LevelAccessor; /** * Interface reserved for flora which need to have different BlockState setup than those from naturally generated */ public interface IPostGenUpdate { void updatePostGen(LevelAccessor worldIn, BlockPos pos); }
335
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
UndergrowthBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/UndergrowthBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.GrassColor; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import java.util.Random; public class UndergrowthBlock extends BushBlock implements BonemealableBlock, net.minecraftforge.common.IForgeShearable { protected OffsetType offset; public UndergrowthBlock(Properties properties) { super(properties); this.offset = OffsetType.NONE; } public UndergrowthBlock(Properties properties, OffsetType type) { super(properties); this.offset = type; } protected boolean mayPlaceOn(BlockState state, BlockGetter worldIn, BlockPos pos) { return state.isFaceSturdy(worldIn, pos, Direction.UP) && !state.is(Blocks.MAGMA_BLOCK); } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return true; } public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) { return true; } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return Shapes.empty(); } public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { if (entityIn instanceof Player && !entityIn.isSteppingCarefully()) { entityIn.makeStuckInBlock(state, new Vec3(0.95F, 1D, 0.95F)); if (worldIn.getRandom().nextInt(20) == 0) { worldIn.playLocalSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.GRASS_STEP, SoundSource.AMBIENT, 1, 1, true); } } } public OffsetType getOffsetType() { return this.offset; } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { return true; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { BlockState blockstate = worldIn.getBlockState(pos); for(int k = 0; k < 3; ++k) { BlockPos blockpos = pos.offset(rand.nextInt(3) - 1, 1 - rand.nextInt(3), rand.nextInt(3) - 1); if (worldIn.isInWorldBounds(blockpos) && worldIn.isEmptyBlock(blockpos) && blockstate.canSurvive(worldIn, blockpos)) { worldIn.setBlock(blockpos, blockstate, 2); } } } }
3,206
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
LardBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/LardBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.BlockParticleOption; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; public class LardBlock extends Block { protected static final VoxelShape SHAPE = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 15.0D, 15.0D); public LardBlock(Block.Properties properties) { super(properties); } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return SHAPE; } public void fallOn(Level worldIn, BlockState state, BlockPos pos, Entity entityIn, float fallDistance) { entityIn.playSound(SoundEvents.HONEY_BLOCK_SLIDE, 1.0F, 1.0F); if (!worldIn.isClientSide) { worldIn.broadcastEntityEvent(entityIn, (byte)54); } if (entityIn.causeFallDamage(fallDistance, 0.2F, DamageSource.FALL)) { entityIn.playSound(this.soundType.getFallSound(), this.soundType.getVolume() * 0.5F, this.soundType.getPitch() * 0.75F); } } public void updateEntityAfterFallOn(BlockGetter getter, Entity entityIn) { if (entityIn.isSuppressingBounce()) { super.updateEntityAfterFallOn(getter, entityIn); } else { //showJumpParticles(entityIn); this.bounceUp(entityIn); } } private void bounceUp(Entity p_56404_) { Vec3 vec3 = p_56404_.getDeltaMovement(); if (vec3.y < 0.0D) { double d0 = p_56404_ instanceof LivingEntity ? 1.0D : 0.8D; p_56404_.setDeltaMovement(vec3.x, -vec3.y * d0, vec3.z); } } public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { if (this.isSlidingDown(pos, entityIn)) { this.doSlideMovement(entityIn); showSlideParticles(entityIn, worldIn, pos); } super.entityInside(state, worldIn, pos, entityIn); } private void doSlideMovement(Entity entityIn) { Vec3 vec3 = entityIn.getDeltaMovement(); if (vec3.y < -0.13D) { double d0 = -0.05D / vec3.y; entityIn.setDeltaMovement(new Vec3(vec3.x * d0, -0.05D, vec3.z * d0)); } else { entityIn.setDeltaMovement(new Vec3(vec3.x, -0.05D, vec3.z)); } entityIn.resetFallDistance(); } private boolean isSlidingDown(BlockPos p_54008_, Entity p_54009_) { if (p_54009_.isOnGround()) { return false; } else if (p_54009_.getY() > (double)p_54008_.getY() + 0.9375D - 1.0E-7D) { return false; } else if (p_54009_.getDeltaMovement().y >= -0.08D) { return false; } else { double d0 = Math.abs((double)p_54008_.getX() + 0.5D - p_54009_.getX()); double d1 = Math.abs((double)p_54008_.getZ() + 0.5D - p_54009_.getZ()); double d2 = 0.4375D + (double)(p_54009_.getBbWidth() / 2.0F); return d0 + 1.0E-7D > d2 || d1 + 1.0E-7D > d2; } } public static void showSlideParticles(Entity entity, Level world, BlockPos pos) { showParticles(entity, world, pos, 5); } public static void showJumpParticles(Entity entity, Level world, BlockPos pos) { showParticles(entity, world, pos, 10); } private static void showParticles(Entity entity, Level world, BlockPos pos, int p_53990_) { if (entity.level.isClientSide) { BlockState blockstate = world.getBlockState(pos); for(int i = 0; i < p_53990_; ++i) { entity.level.addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate), entity.getX(), entity.getY(), entity.getZ(), 0.0D, 0.0D, 0.0D); } } } }
4,280
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CarpetBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/CarpetBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; public class CarpetBlock extends Block { protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 1.0D, 16.0D); public CarpetBlock(Properties p_i48290_2_) { super(p_i48290_2_); } public VoxelShape getShape(BlockState state, BlockGetter p_220053_2_, BlockPos p_220053_3_, CollisionContext p_220053_4_) { return SHAPE; } public BlockState updateShape(BlockState state, Direction direction, BlockState p_196271_3_, LevelAccessor p_196271_4_, BlockPos p_196271_5_, BlockPos p_196271_6_) { return !state.canSurvive(p_196271_4_, p_196271_5_) ? Blocks.AIR.defaultBlockState() : super.updateShape(state, direction, p_196271_3_, p_196271_4_, p_196271_5_, p_196271_6_); } public boolean canSurvive(BlockState p_196260_1_, LevelReader p_196260_2_, BlockPos p_196260_3_) { return !p_196260_2_.isEmptyBlock(p_196260_3_.below()); } }
1,413
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
AlgaeBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/AlgaeBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.FluidTags; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nullable; import java.util.Random; public class AlgaeBlock extends BushBlock implements BonemealableBlock, LiquidBlockContainer, net.minecraftforge.common.IForgeShearable { protected static final VoxelShape SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 12.0D, 14.0D); public AlgaeBlock(BlockBehaviour.Properties properties) { super(properties); } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return SHAPE; } protected boolean mayPlaceOn(BlockState state, BlockGetter worldIn, BlockPos pos) { return state.isFaceSturdy(worldIn, pos, Direction.UP) && !state.is(Blocks.MAGMA_BLOCK); } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos()); return fluidstate.is(FluidTags.WATER) && fluidstate.getAmount() == 8 ? super.getStateForPlacement(context) : null; } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { BlockState blockstate = super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); if (!blockstate.isAir()) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } return blockstate; } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { return true; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { BlockState blockstate = worldIn.getBlockState(pos); for(int k = 0; k < 3; ++k) { BlockPos blockpos = pos.offset(rand.nextInt(3) - 1, 1 - rand.nextInt(3), rand.nextInt(3) - 1); if (worldIn.isInWorldBounds(blockpos) && worldIn.isEmptyBlock(blockpos) && worldIn.getBlockState(blockpos).is(Blocks.WATER) && blockstate.canSurvive(worldIn, blockpos)) { worldIn.setBlock(blockpos, blockstate, 2); } } } public FluidState getFluidState(BlockState p_154537_) { return Fluids.WATER.getSource(false); } public OffsetType getOffsetType() { return OffsetType.XZ; } @Override public boolean canPlaceLiquid(BlockGetter worldIn, BlockPos pos, BlockState state, Fluid fluidIn) { return false; } @Override public boolean placeLiquid(LevelAccessor worldIn, BlockPos pos, BlockState state, FluidState fluidIn) { return false; } }
3,622
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
TallPlantBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/TallPlantBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.SwordItem; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.block.state.properties.PistonType; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.init.ModBlock; import untamedwilds.init.ModItems; import untamedwilds.init.ModTags.ModBlockTags; import javax.annotation.Nullable; import java.util.Random; public class TallPlantBlock extends Block implements BonemealableBlock, IPostGenUpdate { protected static final VoxelShape SHAPE_TRUNK = Block.box(5.0D, 0.0D, 5.0D, 11.0D, 16.0D, 11.0D); protected static final VoxelShape SHAPE_STEM = Block.box(4.0D, 0.0D, 4.0D, 12.0D, 16.0D, 12.0D); protected static final VoxelShape SHAPE_FLOWERING = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 14.0D, 13.0D); public static final IntegerProperty PROPERTY_AGE = BlockStateProperties.AGE_5; public static final IntegerProperty PROPERTY_STAGE = BlockStateProperties.STAGE; public TallPlantBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(PROPERTY_AGE, 0).setValue(PROPERTY_STAGE, 0)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(PROPERTY_AGE, PROPERTY_STAGE); } public OffsetType getOffsetType() { return OffsetType.XZ; } public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) { return true; } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { if (state.getValue(PROPERTY_STAGE) == 1) { return SHAPE_FLOWERING; } Vec3 vector3d = state.getOffset(worldIn, pos); VoxelShape shape = state.getValue(PROPERTY_AGE) == 1 && state.getValue(PROPERTY_STAGE) == 1 ? SHAPE_STEM : SHAPE_TRUNK; return shape.move(vector3d.x, vector3d.y, vector3d.z); } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return true; } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return state.getValue(PROPERTY_STAGE) == 1 ? Shapes.empty() : this.getShape(state, worldIn, pos, context); } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = context.getLevel().getBlockState(context.getClickedPos().below()); if (blockstate.is(ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, 0); } return null; } public void tick(BlockState state, ServerLevel worldIn, BlockPos pos, Random rand) { if (!state.canSurvive(worldIn, pos)) { worldIn.destroyBlock(pos, true); } } public boolean isRandomlyTicking(BlockState state) { return state.getValue(PROPERTY_STAGE) == 0; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { if (state.getValue(PROPERTY_STAGE) == 0 && random.nextInt(8) == 0) { if (worldIn.isEmptyBlock(pos.above()) && worldIn.getLightEmission(pos.above()) >= 9) { int i = this.getNumReedBlocksBelow(worldIn, pos) + 1; if (i < 4 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(worldIn, pos, state, random.nextInt(3) == 0)) { this.grow(worldIn, pos, random, i); net.minecraftforge.common.ForgeHooks.onCropsGrowPost(worldIn, pos, state); } } } } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { return worldIn.getBlockState(pos.below()).is(ModBlockTags.ALOE_PLANTABLE_ON) || worldIn.getBlockState(pos.below()).getBlock() == ModBlock.ZIMBABWE_ALOE.get(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (!stateIn.canSurvive(worldIn, currentPos)) { worldIn.scheduleTick(currentPos, this, 1); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { int i = this.getNumReedBlocksAbove(worldIn, pos); return worldIn.getBlockState(pos.above(i)).getValue(PROPERTY_STAGE) != 1; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); int k = i + j + 1; if (worldIn.getBlockState(pos).getValue(PROPERTY_AGE) == 0) { worldIn.setBlockAndUpdate(pos, this.defaultBlockState().setValue(PROPERTY_AGE, 5)); } else { BlockPos blockpos = pos.above(i); BlockState blockstate = worldIn.getBlockState(blockpos); if (blockstate.getValue(PROPERTY_STAGE) == 1 || !worldIn.isEmptyBlock(blockpos.above())) { return; } this.grow(worldIn, blockpos, rand, k); } } protected void grow(Level worldIn, BlockPos posIn, Random rand, int p_220258_5_) { if ((p_220258_5_ > 2 && rand.nextInt(3) == 0) || p_220258_5_ > 4) { worldIn.setBlockAndUpdate(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 5).setValue(PROPERTY_STAGE, 1)); } else { worldIn.setBlockAndUpdate(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 5)); worldIn.setBlockAndUpdate(posIn, this.defaultBlockState().setValue(PROPERTY_AGE, 4)); int j = 1; for(int i = 3; i >= 0 && worldIn.getBlockState(posIn.below(j)).getBlock() == ModBlock.ZIMBABWE_ALOE.get(); --i) { worldIn.setBlockAndUpdate(posIn.below(j), ModBlock.ZIMBABWE_ALOE.get().defaultBlockState().setValue(PROPERTY_AGE, Math.max(i, 1))); j++; } worldIn.setBlockAndUpdate(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 5)); } } public float getDestroyProgress(BlockState state, Player player, BlockGetter worldIn, BlockPos pos) { return player.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(state, player, worldIn, pos); } protected int getNumReedBlocksAbove(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.above(i + 1)).getBlock() == ModBlock.ZIMBABWE_ALOE.get(); ++i) { } return i; } protected int getNumReedBlocksBelow(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.below(i + 1)).getBlock() == ModBlock.ZIMBABWE_ALOE.get(); ++i) { } return i; } protected ItemLike getSeedsItem() { return ModItems.SEED_ZIMBABWE_ALOE.get(); } public ItemStack getCloneItemStack(BlockGetter p_60261_, BlockPos p_60262_, BlockState p_60263_) { return new ItemStack(this.getSeedsItem()); } public void updatePostGen(LevelAccessor worldIn, BlockPos pos) { int i; for (i = 0; i < 3 && (worldIn.getBlockState(pos.above(i)).isAir() || worldIn.getBlockState(pos.above(i)).getBlock() == ModBlock.ZIMBABWE_ALOE.get()); i++) { worldIn.setBlock(pos.above(i), this.defaultBlockState().setValue(PROPERTY_AGE, Math.max(1, i + 3)), 3); } } }
8,596
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
TallGrassBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/TallGrassBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.init.ModBlock; import untamedwilds.init.ModTags.ModBlockTags; import javax.annotation.Nullable; import java.util.Random; public class TallGrassBlock extends Block implements BonemealableBlock, IPostGenUpdate { protected static final VoxelShape SHAPE_TRUNK = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 16.0D, 13.0D); protected static final VoxelShape SHAPE_FLOWERING = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 14.0D, 13.0D); public static final IntegerProperty PROPERTY_AGE = BlockStateProperties.AGE_3; public static final IntegerProperty PROPERTY_STAGE = BlockStateProperties.STAGE; public TallGrassBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(PROPERTY_AGE, 0).setValue(PROPERTY_STAGE, 0)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(PROPERTY_AGE, PROPERTY_STAGE); } public OffsetType getOffsetType() { return OffsetType.XZ; } public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) { return true; } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { Vec3 vector3d = state.getOffset(worldIn, pos); VoxelShape shape = (state.getValue(PROPERTY_STAGE) == 1 && state.getValue(PROPERTY_AGE) == 3) ? SHAPE_FLOWERING : SHAPE_TRUNK; return shape.move(vector3d.x, vector3d.y, vector3d.z); } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return true; } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return (state.getValue(PROPERTY_STAGE) == 1 && state.getValue(PROPERTY_AGE) == 3) ? Shapes.empty() : this.getShape(state, worldIn, pos, context); } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = context.getLevel().getBlockState(context.getClickedPos().below()); if (blockstate.is(ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, 0); } return null; } public void tick(BlockState state, ServerLevel worldIn, BlockPos pos, Random rand) { if (!state.canSurvive(worldIn, pos)) { worldIn.destroyBlock(pos, true); } } public boolean isRandomlyTicking(BlockState state) { return state.getValue(PROPERTY_STAGE) == 0; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { if (state.getValue(PROPERTY_STAGE) == 0 && random.nextInt(8) == 0) { if (worldIn.isEmptyBlock(pos.above()) && worldIn.getLightEmission(pos.above()) >= 9) { int i = this.getNumReedBlocksBelow(worldIn, pos) + 1; if (i < 4 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(worldIn, pos, state, random.nextInt(3) == 0)) { this.grow(worldIn, pos, i); net.minecraftforge.common.ForgeHooks.onCropsGrowPost(worldIn, pos, state); } } } } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { return worldIn.getBlockState(pos.below()).is(ModBlockTags.ALOE_PLANTABLE_ON) || worldIn.getBlockState(pos.below()).getBlock() == ModBlock.PAMPAS_GRASS.get(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (!stateIn.canSurvive(worldIn, currentPos)) { worldIn.scheduleTick(currentPos, this, 1); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { int i = this.getNumReedBlocksAbove(worldIn, pos); return worldIn.getBlockState(pos.above(i)).getValue(PROPERTY_STAGE) != 1; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); int k = i + j + 1; if (worldIn.getBlockState(pos).getValue(PROPERTY_AGE) == 0) { worldIn.setBlockAndUpdate(pos, this.defaultBlockState().setValue(PROPERTY_AGE, 3)); } else { BlockPos blockpos = pos.above(i); BlockState blockstate = worldIn.getBlockState(blockpos); if (blockstate.getValue(PROPERTY_STAGE) == 1 || !worldIn.isEmptyBlock(blockpos.above())) { return; } this.grow(worldIn, blockpos, k); } } protected void grow(Level worldIn, BlockPos posIn, int p_220258_5_) { worldIn.setBlockAndUpdate(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 3)); worldIn.setBlockAndUpdate(posIn, this.defaultBlockState().setValue(PROPERTY_AGE, 2)); int j = 1; for(int i = 3; i >= 0 && worldIn.getBlockState(posIn.below(j)).getBlock() == ModBlock.PAMPAS_GRASS.get(); --i) { worldIn.setBlockAndUpdate(posIn.below(j), ModBlock.PAMPAS_GRASS.get().defaultBlockState().setValue(PROPERTY_AGE, 1)); j++; } worldIn.setBlockAndUpdate(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 3)); if (p_220258_5_ == 2) { for(int i = 0; i < 3 && worldIn.getBlockState(posIn.above(i)).getBlock() == ModBlock.PAMPAS_GRASS.get(); ++i) { worldIn.setBlock(posIn.above(i), this.defaultBlockState().setValue(PROPERTY_AGE, worldIn.getBlockState(posIn.above(i)).getValue(PROPERTY_AGE)).setValue(PROPERTY_STAGE, 1), 3); } } } public float getDestroyProgress(BlockState state, Player player, BlockGetter worldIn, BlockPos pos) { return player.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(state, player, worldIn, pos); } protected int getNumReedBlocksAbove(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.above(i + 1)).getBlock() == ModBlock.PAMPAS_GRASS.get(); ++i) { } return i; } protected int getNumReedBlocksBelow(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.below(i + 1)).getBlock() == ModBlock.PAMPAS_GRASS.get(); ++i) { } return i; } public void updatePostGen(LevelAccessor worldIn, BlockPos pos) { int i; for (i = 0; i < 3 && (worldIn.getBlockState(pos.above(i)).isAir() || worldIn.getBlockState(pos.above(i)).getBlock() == ModBlock.PAMPAS_GRASS.get()); i++) { worldIn.setBlock(pos.above(i), this.defaultBlockState().setValue(PROPERTY_AGE, Math.max(1, i + 1)), 3); } } }
7,983
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
AnemoneBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/AnemoneBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.tags.FluidTags; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.animal.TropicalFish; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BushBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; public class AnemoneBlock extends BushBlock implements SimpleWaterloggedBlock { public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; private static final VoxelShape SHAPE = Block.box(6.0D, 0.0D, 6.0D, 10.0D, 6.0D, 10.0D); public AnemoneBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.TRUE)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(WATERLOGGED); } public VoxelShape getShape(BlockState p_220053_1_, BlockGetter p_220053_2_, BlockPos p_220053_3_, CollisionContext p_220053_4_) { return SHAPE; } public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = this.defaultBlockState(); FluidState ifluidstate = context.getLevel().getFluidState(context.getClickedPos()); return ifluidstate.is(FluidTags.WATER) && ifluidstate.getAmount() == 8 ? blockstate.setValue(WATERLOGGED, ifluidstate.getType() == Fluids.WATER) : null; } public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } protected boolean isValidGround(BlockState state, BlockGetter worldIn, BlockPos pos) { return !state.getCollisionShape(worldIn, pos).getFaceShape(Direction.UP).isEmpty(); } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { BlockPos blockpos = pos.below(); return this.isValidGround(worldIn.getBlockState(blockpos), worldIn, blockpos); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (stateIn.getValue(WATERLOGGED)) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } @Override public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { if (!world.isClientSide && entity instanceof LivingEntity) { if (!(entity instanceof TropicalFish)) { ((LivingEntity)entity).addEffect(new MobEffectInstance(MobEffects.POISON, 80, 0)); } } } }
3,754
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
StrangeEggBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/StrangeEggBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.block.blockentity.EggBlockEntity; import java.util.Random; public class StrangeEggBlock extends Block implements SimpleWaterloggedBlock, EntityBlock { protected static final VoxelShape SHAPE = Block.box(4.0D, 0.0D, 4.0D, 12.0D, 12.0D, 12.0D); public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public StrangeEggBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(WATERLOGGED); } public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = this.defaultBlockState(); FluidState fluidState = context.getLevel().getFluidState(context.getClickedPos()); return blockstate.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); } public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } public VoxelShape getShape(BlockState state, BlockGetter getter, BlockPos pos, CollisionContext collision) { return SHAPE; } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { BlockPos blockpos = pos.below(); return this.isValidGround(worldIn.getBlockState(blockpos), worldIn, blockpos); } protected boolean isValidGround(BlockState state, BlockGetter worldIn, BlockPos pos) { return !state.getCollisionShape(worldIn, pos).getFaceShape(Direction.UP).isEmpty(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (stateIn.getValue(WATERLOGGED)) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } if (!canSurvive(stateIn, worldIn, currentPos)) { worldIn.destroyBlock(currentPos, false); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new EggBlockEntity(pos, state); } public boolean isRandomlyTicking(BlockState state) { return true; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { boolean canHatch = worldIn.isWaterAt(pos); if (worldIn.getBlockEntity(pos) instanceof EggBlockEntity egg) { egg.setCanSpawn(this.canHatch(state, worldIn, pos, random)); egg.releaseOrCreateMob(worldIn); } } public boolean canHatch(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { return true; } }
4,001
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
TitanArumBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/TitanArumBlock.java
package untamedwilds.block; import com.mojang.math.Vector3f; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.DustParticleOptions; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.AreaEffectCloud; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.block.state.properties.RedstoneSide; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.init.ModBlock; import untamedwilds.init.ModItems; import untamedwilds.init.ModTags.ModBlockTags; import javax.annotation.Nullable; import java.util.Random; public class TitanArumBlock extends Block implements BonemealableBlock, IPostGenUpdate { protected static final VoxelShape SHAPE_NORMAL = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 16.0D, 14.0D); protected static final VoxelShape SHAPE_SPATHE = Block.box(5.0D, 0.0D, 5.0D, 11.0D, 16.0D, 11.0D); protected static final VoxelShape SHAPE_CORM = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 1.0D, 14.0D); public static final IntegerProperty PROPERTY_AGE = BlockStateProperties.AGE_5; // AGE 5 is not used public static final IntegerProperty PROPERTY_STAGE = BlockStateProperties.STAGE; public TitanArumBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(PROPERTY_AGE, 0).setValue(PROPERTY_STAGE, 0)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(PROPERTY_AGE, PROPERTY_STAGE); } public OffsetType getOffsetType() { return OffsetType.XZ; } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { if (state.getValue(PROPERTY_AGE) == 0) { return SHAPE_CORM; } Vec3 vector3d = state.getOffset(worldIn, pos); VoxelShape shape = state.getValue(PROPERTY_AGE) == 1 && state.getValue(PROPERTY_STAGE) == 1 ? SHAPE_NORMAL : SHAPE_SPATHE; return shape.move(vector3d.x, vector3d.y, vector3d.z); } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return true; } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return this.getShape(state, worldIn, pos, context); } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = context.getLevel().getBlockState(context.getClickedPos().below()); if (blockstate.is(ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, 0); } return null; } public void tick(BlockState state, ServerLevel worldIn, BlockPos pos, Random rand) { if (!state.canSurvive(worldIn, pos)) { worldIn.destroyBlock(pos, true); } } public boolean isRandomlyTicking(BlockState state) { return state.getValue(PROPERTY_STAGE) == 0; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { if (state.getValue(PROPERTY_STAGE) == 0 && random.nextInt(8) == 0) { if (worldIn.isEmptyBlock(pos.above()) && worldIn.getLightEmission(pos.above()) >= 9) { int i = this.getNumReedBlocksBelow(worldIn, pos) + 1; if (i < 4 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(worldIn, pos, state, random.nextInt(3) == 0)) { this.grow(state, worldIn, pos, random, i); net.minecraftforge.common.ForgeHooks.onCropsGrowPost(worldIn, pos, state); } } } // TODO: Re-enable mob luring in the future /* if (state.get(PROPERTY_STAGE) == 1 && state.get(PROPERTY_AGE) > 1) { List<MobEntity> list = worldIn.getEntitiesOfClass(MobEntity.class, VoxelShapes.fullCube().getBoundingBox().inflate(12, 4, 12)); list.removeIf(input -> !(input.getCreatureAttribute() == CreatureAttribute.ARTHROPOD || input.getCreatureAttribute() == CreatureAttribute.UNDEAD || input.getTarget() != null)); if (!list.isEmpty()) { MobEntity lured_entity = list.get(random.nextInt(list.size())); EntityUtils.spawnParticlesOnEntity(worldIn, lured_entity, ParticleTypes.END_ROD, 8, 1); lured_entity.getNavigation().tryMoveToXYZ(pos.getX() + random.nextInt(6) - 3, pos.getY(), pos.getZ() + random.nextInt(6) - 3, 1); } // Attract Undead and Arthropods, spawn new ones 10% of the time? } */ } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { return worldIn.getBlockState(pos.below()).is(ModBlockTags.REEDS_PLANTABLE_ON) || worldIn.getBlockState(pos.below()).getBlock() == ModBlock.TITAN_ARUM.get(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (!stateIn.canSurvive(worldIn, currentPos)) { worldIn.scheduleTick(currentPos, this, 1); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); return i + j + 1 < 4 && worldIn.getBlockState(pos.above(i)).getValue(PROPERTY_STAGE) != 1; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); int k = i + j + 1; if (j < 3) { BlockPos blockpos = pos.above(i); BlockState blockstate = worldIn.getBlockState(blockpos); if (worldIn.getBlockState(pos.below()).getBlock() == ModBlock.TITAN_ARUM.get() || blockstate.getValue(PROPERTY_STAGE) == 1 || !worldIn.isEmptyBlock(blockpos.above())) { return; } if (k >= 3) { this.makeAreaOfEffectCloud(worldIn, pos); for(i = 0; i < 3 && worldIn.getBlockState(pos.above(i)).getBlock() == ModBlock.TITAN_ARUM.get(); ++i) { worldIn.setBlock(pos.above(i), this.defaultBlockState().setValue(PROPERTY_AGE, worldIn.getBlockState(pos.above(i)).getValue(PROPERTY_AGE)).setValue(PROPERTY_STAGE, 1), 3); } for(int l = 0; l < 3; ++l) { BlockPos seed_pos = pos.offset(rand.nextInt(3) - 1, 1 - rand.nextInt(3), rand.nextInt(3) - 1); if (worldIn.isInWorldBounds(seed_pos) && worldIn.getBlockState(seed_pos).is(Blocks.WATER) && blockstate.canSurvive(worldIn, seed_pos)) { worldIn.setBlock(seed_pos, ModBlock.TITAN_ARUM.get().defaultBlockState().setValue(PROPERTY_STAGE, 1), 2); } } return; } this.grow(blockstate, worldIn, blockpos, rand, k); } } protected void grow(BlockState blockStateIn, Level worldIn, BlockPos posIn, Random rand, int p_220258_5_) { int l = blockStateIn.getValue(PROPERTY_AGE); if (l == 0) { worldIn.setBlockAndUpdate(posIn, this.defaultBlockState().setValue(PROPERTY_AGE, 1)); } else { worldIn.setBlock(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, Math.min(3, l + 1)).setValue(PROPERTY_STAGE, 0), 3); } } public float getDestroyProgress(BlockState state, Player player, BlockGetter worldIn, BlockPos pos) { return player.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(state, player, worldIn, pos); } protected int getNumReedBlocksAbove(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.above(i + 1)).getBlock() == ModBlock.TITAN_ARUM.get(); ++i) { } return i; } protected int getNumReedBlocksBelow(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.below(i + 1)).getBlock() == ModBlock.TITAN_ARUM.get(); ++i) { } return i; } private void makeAreaOfEffectCloud(Level worldIn, BlockPos pos) { AreaEffectCloud areaeffectcloudentity = new AreaEffectCloud(worldIn, pos.getX() + 0.5, pos.getY() - worldIn.getBlockState(pos).getValue(PROPERTY_AGE), pos.getZ() + 0.5); areaeffectcloudentity.setRadius(6.0F); areaeffectcloudentity.setRadiusOnUse(-0.2F); areaeffectcloudentity.setWaitTime(10); areaeffectcloudentity.setRadiusPerTick(-areaeffectcloudentity.getRadius() / ((float)areaeffectcloudentity.getDuration() * 0.5F)); areaeffectcloudentity.setFixedColor(5599028); areaeffectcloudentity.addEffect(new MobEffectInstance(MobEffects.CONFUSION, 80, 0, true, false)); worldIn.addFreshEntity(areaeffectcloudentity); } public ItemStack getCloneItemStack(BlockGetter p_60261_, BlockPos p_60262_, BlockState p_60263_) { return new ItemStack(ModItems.SEED_TITAN_ARUM.get()); } public void updatePostGen(LevelAccessor worldIn, BlockPos pos) { for (int i = 0; i < 3 && (worldIn.getBlockState(pos.above(i)).isAir() || worldIn.getBlockState(pos.above(i)).getBlock() == ModBlock.TITAN_ARUM.get()); i++) { worldIn.setBlock(pos.above(i), this.defaultBlockState().setValue(PROPERTY_AGE, i + 1).setValue(PROPERTY_STAGE, 1), 3); } } }
10,502
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CageBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/CageBlock.java
package untamedwilds.block; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.BlockSource; import net.minecraft.core.Direction; import net.minecraft.core.dispenser.DispenseItemBehavior; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.context.DirectionalPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.DispenserBlock; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import untamedwilds.block.blockentity.CageBlockEntity; import untamedwilds.init.ModBlock; import untamedwilds.util.EntityUtils; import javax.annotation.Nullable; import java.util.List; import java.util.Random; public class CageBlock extends Block implements SimpleWaterloggedBlock, EntityBlock { public static final BooleanProperty OPEN = BlockStateProperties.OPEN; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; private static final VoxelShape CAGE_COLLISION_AABB_EMPTY = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 2.0D, 15.0D); private static final VoxelShape CAGE_COLLISION_AABB_FULL = Block.box(1.0D, 0.0D, 1.0D, 15.0D, 15.0D, 15.0D); public CageBlock(Block.Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(OPEN, Boolean.FALSE).setValue(WATERLOGGED, Boolean.FALSE)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(OPEN, WATERLOGGED); } public void playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { this.spawnDestroyParticles(worldIn, player, pos, state); if (!worldIn.isClientSide) { BlockEntity tileentity = worldIn.getBlockEntity(pos); if (tileentity instanceof CageBlockEntity te) { ItemStack itemstack = new ItemStack(ModBlock.TRAP_CAGE.get()); CompoundTag compound = new CompoundTag(); if (te.hasTagCompound() && te.isLocked()) { compound.putBoolean("closed", te.isLocked()); compound.put("EntityTag", te.getTagCompound().getCompound("EntityTag")); itemstack.setTag(compound); } popResource(worldIn, pos, itemstack); worldIn.updateNeighbourForOutputSignal(pos, state.getBlock()); } else { super.playerWillDestroy(worldIn, pos, state, player); } } } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return state.getValue(OPEN) ? CAGE_COLLISION_AABB_EMPTY : CAGE_COLLISION_AABB_FULL; } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return state.getValue(OPEN); } public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = this.defaultBlockState(); FluidState fluidstate = context.getLevel().getFluidState(context.getClickedPos()); return blockstate.setValue(OPEN, Boolean.TRUE).setValue(WATERLOGGED, fluidstate.getType() == Fluids.WATER); } public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { super.setPlacedBy(worldIn, pos, state, placer, stack); if (stack.hasTag()) { BlockEntity te = worldIn.getBlockEntity(pos); if (stack.getTag() != null && te instanceof CageBlockEntity blockEntity) { te.load(stack.getTag()); if (blockEntity.isLocked() && blockEntity.hasTagCompound()) { worldIn.setBlockAndUpdate(pos, state.setValue(OPEN, Boolean.FALSE)); } } } } public void neighborChanged(BlockState state, Level worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) { if (!worldIn.isClientSide) { if (worldIn.hasNeighborSignal(pos)) { trySpawningEntity(state, (ServerLevel) worldIn, pos); } } } public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (stateIn.getValue(WATERLOGGED)) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult hit) { if (playerIn.isSteppingCarefully() || worldIn.isClientSide || state.getValue(OPEN)) { return InteractionResult.FAIL; } else { boolean success = trySpawningEntity(state, (ServerLevel) worldIn, pos); return success ? InteractionResult.SUCCESS : InteractionResult.FAIL; } } private boolean trySpawningEntity(BlockState state, ServerLevel worldIn, BlockPos pos) { CageBlockEntity te = (CageBlockEntity)worldIn.getBlockEntity(pos); BlockPos check = pos.below(); if (te != null) { BlockPos spawnpos = /*!worldIn.getBlockState(check).isSolid() ? pos :*/ new BlockPos(pos.getX(), pos.getY() + 1F, pos.getZ()); if (te.spawnCagedCreature(worldIn, spawnpos, worldIn.isEmptyBlock(check))) { spawnParticles(worldIn, pos, ParticleTypes.POOF); worldIn.playSound(null, pos, SoundEvents.WOODEN_PRESSURE_PLATE_CLICK_ON, SoundSource.BLOCKS, 0.3F, 0.8F); worldIn.setBlockAndUpdate(pos, state.setValue(OPEN, Boolean.TRUE)); return true; } else { spawnParticles(worldIn, pos, ParticleTypes.SMOKE); worldIn.playSound(null, pos, SoundEvents.WOODEN_PRESSURE_PLATE_CLICK_OFF, SoundSource.BLOCKS, 0.3F, 0.6F); } } return false; } private <T extends ParticleOptions> void spawnParticles(Level worldIn, BlockPos pos, T particle) { Random random = worldIn.getRandom(); float d3 = random.nextFloat() * 0.02F; float d1 = random.nextFloat() * 0.02F; float d2 = random.nextFloat() * 0.02F; ((ServerLevel)worldIn).sendParticles(particle, pos.getX() + random.nextFloat(), pos.getY(), pos.getZ() + random.nextFloat(), 15, d3, d1, d2, 0.12F); } @Override public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { CageBlockEntity te = (CageBlockEntity)world.getBlockEntity(pos); if (!world.isClientSide && !(entity instanceof Player) && entity.isAlive() && entity instanceof LivingEntity) { if (te != null && !te.isLocked() && entity instanceof Mob) { if (te.cageEntity((Mob) entity)) { world.playSound(null, pos, SoundEvents.WOODEN_PRESSURE_PLATE_CLICK_ON, SoundSource.BLOCKS, 0.3F, 0.8F); world.setBlockAndUpdate(pos, state.setValue(OPEN, Boolean.FALSE)); spawnParticles(world, pos, ParticleTypes.POOF); } } } } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) { if (stack.getTag() != null) { EntityType<?> type = EntityUtils.getEntityTypeFromTag(stack.getTag(), null); if (type != null) { EntityUtils.buildTooltipData(stack, tooltip, type, EntityUtils.getVariantName(type, stack.getTag().getCompound("EntityTag").getInt("Variant"))); } } else { tooltip.add(new TranslatableComponent("block.trap_cage.state_empty").withStyle(ChatFormatting.GRAY)); } } @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new CageBlockEntity(pos, state); } public static class DispenserBehaviorTrapCage implements DispenseItemBehavior { public ItemStack dispense(BlockSource source, ItemStack stack) { Item item = stack.getItem(); if (item instanceof BlockItem) { Direction direction = source.getBlockState().getValue(DispenserBlock.FACING); BlockPos blockpos = source.getPos().relative(direction); Direction direction1 = source.getLevel().isEmptyBlock(blockpos.below()) ? direction : Direction.UP; boolean successful = ((BlockItem)item).place(new DirectionalPlaceContext(source.getLevel(), blockpos, direction, stack, direction1)) == InteractionResult.SUCCESS; } return stack; } protected void playDispenseSound(BlockSource source) { source.getLevel().globalLevelEvent(1000, source.getPos(), 0); } } }
11,049
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EpyphitePlantBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/EpyphitePlantBlock.java
package untamedwilds.block; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.DirectionProperty; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nullable; import java.util.Map; public class EpyphitePlantBlock extends HorizontalDirectionalBlock { public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; private static final Map<Direction, VoxelShape> SHAPES = Maps.newEnumMap(ImmutableMap.of( Direction.NORTH, Block.box(1D, 1D, 15D, 15D, 15D, 16D), Direction.SOUTH, Block.box(1D, 1D, 0.0D, 15D, 15D, 1D), Direction.WEST, Block.box(15D, 1D, 1D, 16D, 15D, 15D), Direction.EAST, Block.box(0.0D, 1D, 1D, 1D, 15D, 15D))); public EpyphitePlantBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.NORTH)); } public BlockState mirror(BlockState state, Mirror mirrorIn) { return state.rotate(mirrorIn.getRotation(state.getValue(FACING))); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(FACING); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { return facing.getOpposite() == stateIn.getValue(FACING) && !stateIn.canSurvive(worldIn, currentPos) ? Blocks.AIR.defaultBlockState() : stateIn; } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return SHAPES.get(state.getValue(FACING)); } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { Direction direction = state.getValue(FACING); BlockPos blockpos = pos.relative(direction.getOpposite()); BlockState blockstate = worldIn.getBlockState(blockpos); return blockstate.isFaceSturdy(worldIn, blockpos, direction); } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = super.getStateForPlacement(context); LevelReader iworldreader = context.getLevel(); BlockPos blockpos = context.getClickedPos(); Direction[] adirection = context.getNearestLookingDirections(); for(Direction direction : adirection) { if (direction.getAxis().isHorizontal()) { blockstate = blockstate.setValue(FACING, direction.getOpposite()); if (blockstate.canSurvive(iworldreader, blockpos)) { return blockstate; } } } return null; } }
3,486
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CritterBurrowBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/CritterBurrowBlock.java
package untamedwilds.block; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.block.blockentity.CritterBurrowBlockEntity; import untamedwilds.init.ModItems; import java.util.Random; public class CritterBurrowBlock extends Block implements SimpleWaterloggedBlock, EntityBlock { protected static final VoxelShape SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 2.0D, 16.0D); public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public CritterBurrowBlock(Block.Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(WATERLOGGED); } public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = this.defaultBlockState(); FluidState fluidState = context.getLevel().getFluidState(context.getClickedPos()); return blockstate.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); } public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } public VoxelShape getShape(BlockState state, BlockGetter getter, BlockPos pos, CollisionContext collision) { return SHAPE; } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { BlockPos blockpos = pos.below(); return this.isValidGround(worldIn.getBlockState(blockpos), worldIn, blockpos); } protected boolean isValidGround(BlockState state, BlockGetter worldIn, BlockPos pos) { return !state.getCollisionShape(worldIn, pos).getFaceShape(Direction.UP).isEmpty(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (stateIn.getValue(WATERLOGGED)) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } if (!canSurvive(stateIn, worldIn, currentPos)) { worldIn.destroyBlock(currentPos, false); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new CritterBurrowBlockEntity(pos, state); } @Override public int getExpDrop(BlockState state, net.minecraft.world.level.LevelReader world, BlockPos pos, int fortune, int silktouch) { return 10 + RANDOM.nextInt(10); } public boolean isRandomlyTicking(BlockState state) { return true; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { if (worldIn.getBlockEntity(pos) instanceof CritterBurrowBlockEntity burrow) { burrow.releaseOrCreateMob(worldIn); } } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult hit) { if (worldIn.isClientSide || hand.equals(InteractionHand.OFF_HAND)) { return InteractionResult.FAIL; } else { CritterBurrowBlockEntity te = (CritterBurrowBlockEntity) worldIn.getBlockEntity(pos); if (playerIn.isCreative() && te != null) { if (playerIn.isSteppingCarefully()) te.releaseOrCreateMob((ServerLevel) worldIn); else { playerIn.sendMessage(new TranslatableComponent("This burrow contains " + te.getEntityType().getDescriptionId()).withStyle(ChatFormatting.ITALIC), playerIn.getUUID()); playerIn.sendMessage(new TranslatableComponent("The variant is " + te.getVariant()).withStyle(ChatFormatting.ITALIC), playerIn.getUUID()); playerIn.sendMessage(new TranslatableComponent("There are " + (te.getInhabitants().size() + te.getCount()) + " mobs inside the burrow (" + te.getInhabitants().size() + " stored, and " + te.getCount() + " to be spawned)").withStyle(ChatFormatting.ITALIC), playerIn.getUUID()); } } else { playerIn.sendMessage(new TranslatableComponent("block.burrow.state", te.getEntityType().getDescription().getString()), playerIn.getUUID()); } return InteractionResult.SUCCESS; } } }
5,912
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CustomGrassBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/CustomGrassBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import java.util.Random; public class CustomGrassBlock extends FlowerBlock implements BonemealableBlock { protected static final float AABB_OFFSET = 6.0F; protected static final VoxelShape SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 13.0D, 14.0D); public CustomGrassBlock(MobEffect p_53512_, int p_53513_, BlockBehaviour.Properties p_53514_) { super(p_53512_, p_53513_, p_53514_); } public VoxelShape getShape(BlockState p_53517_, BlockGetter p_53518_, BlockPos p_53519_, CollisionContext p_53520_) { Vec3 vec3 = p_53517_.getOffset(p_53518_, p_53519_); return SHAPE.move(vec3.x, vec3.y, vec3.z); } public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } public boolean isValidBonemealTarget(BlockGetter p_153797_, BlockPos p_153798_, BlockState p_153799_, boolean p_153800_) { return p_153797_.getBlockState(p_153798_.above()).isAir(); } public boolean isBonemealSuccess(Level p_153802_, Random p_153803_, BlockPos p_153804_, BlockState p_153805_) { return true; } public void performBonemeal(ServerLevel p_57298_, Random p_57299_, BlockPos p_57300_, BlockState p_57301_) { popResource(p_57298_, p_57300_, new ItemStack(this)); } }
1,876
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
FloatingPlantBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/FloatingPlantBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.animal.WaterAnimal; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.BushBlock; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.entity.ComplexMobAquatic; import java.util.Random; public class FloatingPlantBlock extends BushBlock implements BonemealableBlock { protected static final VoxelShape SHAPE_NORMAL = Block.box(3.0D, 0.0D, 3.0D, 13.0D, 12D, 13.0D); public FloatingPlantBlock(BlockBehaviour.Properties builder) { super(builder); } public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { if (entityIn instanceof LivingEntity && !(entityIn instanceof WaterAnimal) && !(entityIn instanceof ComplexMobAquatic) && entityIn.isInWater() && !entityIn.isSteppingCarefully()) { entityIn.makeStuckInBlock(state, new Vec3(0.98F, 1D, 0.98F)); if (worldIn.getRandom().nextInt(20) == 0) { worldIn.playLocalSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.WET_GRASS_STEP, SoundSource.AMBIENT, 1, 1, true); } } } public OffsetType getOffsetType() { return OffsetType.XZ; } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { Vec3 vector3d = state.getOffset(worldIn, pos); return SHAPE_NORMAL.move(vector3d.x, vector3d.y, vector3d.z); } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return true; } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return Shapes.empty(); } protected boolean isValidGround(BlockState state, BlockGetter worldIn, BlockPos pos) { FluidState fluidstate = worldIn.getFluidState(pos); FluidState fluidstate1 = worldIn.getFluidState(pos.above()); return (fluidstate.getType() == Fluids.WATER || state.getMaterial() == Material.ICE) && fluidstate1.getType() == Fluids.EMPTY; } @Override public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { BlockPos blockpos = pos.below(); return this.isValidGround(worldIn.getBlockState(blockpos), worldIn, blockpos); } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { return true; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { BlockState blockstate = worldIn.getBlockState(pos); for(int k = 0; k < 3; ++k) { BlockPos blockpos = pos.offset(rand.nextInt(3) - 1, 1 - rand.nextInt(3), rand.nextInt(3) - 1); if (worldIn.isInWorldBounds(blockpos) && worldIn.isEmptyBlock(blockpos) && worldIn.getBlockState(blockpos).is(Blocks.WATER) && blockstate.canSurvive(worldIn, blockpos)) { worldIn.setBlock(blockpos, blockstate, 2); } } } }
4,204
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
NestReptileBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/NestReptileBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.registries.ForgeRegistries; import untamedwilds.UntamedWilds; import untamedwilds.block.blockentity.ReptileNestBlockEntity; import untamedwilds.config.ConfigMobControl; import java.util.Random; public class NestReptileBlock extends Block implements SimpleWaterloggedBlock, EntityBlock { protected static final VoxelShape SHAPE = Block.box(1D, 0.0D, 1D, 15D, 3.5D, 15D); public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public NestReptileBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(WATERLOGGED); } public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = this.defaultBlockState(); FluidState fluidState = context.getLevel().getFluidState(context.getClickedPos()); return blockstate.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); } public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } public VoxelShape getShape(BlockState state, BlockGetter getter, BlockPos pos, CollisionContext collision) { return SHAPE; } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { BlockPos blockpos = pos.below(); return this.isValidGround(worldIn.getBlockState(blockpos), worldIn, blockpos); } protected boolean isValidGround(BlockState state, BlockGetter worldIn, BlockPos pos) { return !state.getCollisionShape(worldIn, pos).getFaceShape(Direction.UP).isEmpty(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (stateIn.getValue(WATERLOGGED)) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } if (!canSurvive(stateIn, worldIn, currentPos)) { worldIn.destroyBlock(currentPos, false); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new ReptileNestBlockEntity(pos, state); } public void fallOn(Level levelIn, BlockState stateIn, BlockPos posIn, Entity entityIn, float p_154849_) { ReptileNestBlockEntity te = (ReptileNestBlockEntity) levelIn.getBlockEntity(posIn); if (te != null && !entityIn.getType().equals(te.getEntityType())) { te.trampleOnNest(levelIn, posIn, stateIn); } super.fallOn(levelIn, stateIn, posIn, entityIn, p_154849_); } public boolean isRandomlyTicking(BlockState state) { return true; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { if (ConfigMobControl.tickingNests.get() && worldIn.getBlockEntity(pos) instanceof ReptileNestBlockEntity burrow) { burrow.createMobs(worldIn); } } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult hit) { if (worldIn.isClientSide || hand.equals(InteractionHand.OFF_HAND)) { return InteractionResult.FAIL; } else { ReptileNestBlockEntity te = (ReptileNestBlockEntity) worldIn.getBlockEntity(pos); if (te != null) { if (playerIn.isCreative() && playerIn.isSteppingCarefully()) { UntamedWilds.LOGGER.info(te.getEggCount()); // TODO: DEBUG } else { te.removeEggs(worldIn, 1); CompoundTag baseTag = new CompoundTag(); ItemStack item = new ItemStack(ForgeRegistries.ITEMS.getValue(new ResourceLocation(UntamedWilds.MOD_ID + ":egg_" + te.getEntityType().getRegistryName().getPath()))); baseTag.putInt("variant", te.getVariant()); baseTag.putInt("custom_model_data", te.getVariant()); item.setTag(baseTag); playerIn.getInventory().add(item); } } return InteractionResult.SUCCESS; } } }
6,003
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ReedBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/ReedBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.animal.WaterAnimal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.SwordItem; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import untamedwilds.entity.ComplexMobAquatic; import untamedwilds.init.ModBlock; import untamedwilds.init.ModTags.ModBlockTags; import javax.annotation.Nullable; import java.util.Random; public class ReedBlock extends Block implements BonemealableBlock, SimpleWaterloggedBlock { protected static final VoxelShape SHAPE_NORMAL = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 16.0D, 14.0D); public static final IntegerProperty PROPERTY_AGE = BlockStateProperties.AGE_2; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final IntegerProperty PROPERTY_STAGE = BlockStateProperties.STAGE; public ReedBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(PROPERTY_AGE, 0).setValue(PROPERTY_STAGE, 0).setValue(WATERLOGGED, Boolean.FALSE)); } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(PROPERTY_AGE, PROPERTY_STAGE, WATERLOGGED); } public OffsetType getOffsetType() { return OffsetType.XZ; } public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) { return true; } public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { Vec3 vector3d = state.getOffset(worldIn, pos); return SHAPE_NORMAL.move(vector3d.x, vector3d.y, vector3d.z); } public boolean isPathfindable(BlockState state, BlockGetter worldIn, BlockPos pos, PathComputationType type) { return true; } public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return Shapes.empty(); } @Nullable public BlockState getStateForWorldgen(LevelAccessor world, BlockPos pos) { boolean isWaterLogged = !world.getFluidState(pos).isEmpty(); BlockState blockstate = world.getBlockState(pos.below()); if (blockstate.getBlock() == ModBlock.COMMON_REED.get()) { if (world.getFluidState(pos.below()).isEmpty() || world.getBlockState(pos.below(2)).getBlock() == ModBlock.COMMON_REED.get()) { world.setBlock(pos.below(), blockstate.setValue(PROPERTY_AGE, 1), 1); } BlockState blockstate1 = world.getBlockState(pos.above()); return blockstate1.getBlock() != ModBlock.COMMON_REED.get() ? ModBlock.COMMON_REED.get().defaultBlockState().setValue(PROPERTY_AGE, 0).setValue(WATERLOGGED, isWaterLogged) : this.defaultBlockState().setValue(PROPERTY_AGE, 1).setValue(WATERLOGGED, isWaterLogged); } if (blockstate.is(ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, isWaterLogged ? 2 : 0).setValue(WATERLOGGED, isWaterLogged); } else { return null; } } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { boolean isWaterLogged = !context.getLevel().getFluidState(context.getClickedPos()).isEmpty(); BlockState blockstate = context.getLevel().getBlockState(context.getClickedPos().below()); if (blockstate.getBlock() == ModBlock.COMMON_REED.get()) { if (context.getLevel().getFluidState(context.getClickedPos().below()).isEmpty() || context.getLevel().getBlockState(context.getClickedPos().below(2)).getBlock() == ModBlock.COMMON_REED.get()) { context.getLevel().setBlockAndUpdate(context.getClickedPos().below(), blockstate.setValue(PROPERTY_AGE, 1)); } BlockState blockstate1 = context.getLevel().getBlockState(context.getClickedPos().above()); return blockstate1.getBlock() != ModBlock.COMMON_REED.get() ? ModBlock.COMMON_REED.get().defaultBlockState().setValue(PROPERTY_AGE, 0).setValue(WATERLOGGED, isWaterLogged) : this.defaultBlockState().setValue(PROPERTY_AGE, 1).setValue(WATERLOGGED, isWaterLogged); } if (blockstate.is(ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, isWaterLogged ? 2 : 0).setValue(WATERLOGGED, isWaterLogged); } else { return null; } } public void tick(BlockState state, ServerLevel worldIn, BlockPos pos, Random rand) { if (!state.canSurvive(worldIn, pos)) { worldIn.destroyBlock(pos, true); } } public boolean isRandomlyTicking(BlockState state) { return state.getValue(PROPERTY_STAGE) == 0; } public void randomTick(BlockState state, ServerLevel worldIn, BlockPos pos, Random random) { if (state.getValue(PROPERTY_STAGE) == 0 && random.nextInt(8) == 0) { if (worldIn.isEmptyBlock(pos.above()) && worldIn.getLightEmission(pos.above()) >= 9) { int i = this.getNumReedBlocksBelow(worldIn, pos) + 1; if (i < 4 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(worldIn, pos, state, random.nextInt(3) == 0)) { this.grow(state, worldIn, pos, random, i); net.minecraftforge.common.ForgeHooks.onCropsGrowPost(worldIn, pos, state); } } } } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { return worldIn.getBlockState(pos.below()).is(ModBlockTags.REEDS_PLANTABLE_ON) || worldIn.getBlockState(pos.below()).getBlock() == ModBlock.COMMON_REED.get(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (stateIn.getValue(WATERLOGGED)) { worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn)); } if (!stateIn.canSurvive(worldIn, currentPos)) { worldIn.scheduleTick(currentPos, this, 1); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); return i + j + 1 < 4 && worldIn.getBlockState(pos.above(i)).getValue(PROPERTY_STAGE) != 1; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); int k = i + j + 1; int l = 1 + rand.nextInt(2); for(int i1 = 0; i1 < l; ++i1) { BlockPos blockpos = pos.above(i); BlockState blockstate = worldIn.getBlockState(blockpos); if (k >= 4 || blockstate.getValue(PROPERTY_STAGE) == 1 || !worldIn.isEmptyBlock(blockpos.above())) { return; } this.grow(blockstate, worldIn, blockpos, rand, k); ++i; ++k; } } protected void grow(BlockState blockStateIn, Level worldIn, BlockPos posIn, Random rand, int p_220258_5_) { BlockState blockstate = worldIn.getBlockState(posIn.below()); int i = blockStateIn.getValue(PROPERTY_AGE) != 1 && blockstate.getBlock() != ModBlock.COMMON_REED.get() ? 0 : 1; int j = (p_220258_5_ < 1 || !(rand.nextFloat() < 0.4F)) && p_220258_5_ != 4 ? 0 : 1; if (blockStateIn.getValue(PROPERTY_AGE) != 2) { worldIn.setBlock(posIn, this.defaultBlockState().setValue(PROPERTY_AGE, 1).setValue(PROPERTY_STAGE, j), 3); } worldIn.setBlock(posIn.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 0).setValue(PROPERTY_STAGE, j), 3); } public float getDestroyProgress(BlockState state, Player player, BlockGetter worldIn, BlockPos pos) { return player.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(state, player, worldIn, pos); } public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { if (entityIn instanceof LivingEntity && !(entityIn instanceof WaterAnimal) && !(entityIn instanceof ComplexMobAquatic) && !entityIn.isInWater() && !entityIn.isSteppingCarefully()) { entityIn.makeStuckInBlock(state, new Vec3(0.95F, 1D, 0.95F)); if (worldIn.getRandom().nextInt(20) == 0) { worldIn.playLocalSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.GRASS_STEP, SoundSource.AMBIENT, 1, 1, true); } } } protected int getNumReedBlocksAbove(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.above(i + 1)).getBlock() == ModBlock.COMMON_REED.get(); ++i) { } return i; } protected int getNumReedBlocksBelow(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.below(i + 1)).getBlock() == ModBlock.COMMON_REED.get(); ++i) { } return i; } public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } }
10,747
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
UndergrowthPoisonousBlock.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/UndergrowthPoisonousBlock.java
package untamedwilds.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.phys.Vec3; import untamedwilds.init.ModBlock; import untamedwilds.init.ModTags; import javax.annotation.Nullable; import java.util.Random; public class UndergrowthPoisonousBlock extends UndergrowthBlock implements BonemealableBlock, IPostGenUpdate, net.minecraftforge.common.IForgeShearable { public static final IntegerProperty PROPERTY_AGE = BlockStateProperties.AGE_2; public UndergrowthPoisonousBlock(Properties properties, OffsetType type) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(PROPERTY_AGE, 0)); this.offset = type; } protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(PROPERTY_AGE); } public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { if (entityIn instanceof LivingEntity && !entityIn.isSteppingCarefully() && entityIn.getBbHeight() > 1) { ((LivingEntity)entityIn).addEffect(new MobEffectInstance(MobEffects.POISON, 100, 1)); entityIn.makeStuckInBlock(state, new Vec3(0.95F, 1D, 0.95F)); if (worldIn.getRandom().nextInt(20) == 0) { worldIn.playLocalSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.GRASS_STEP, SoundSource.AMBIENT, 1, 1, true); } } } @Nullable public BlockState getStateForWorldgen(LevelAccessor world, BlockPos pos) { BlockState blockstate = world.getBlockState(pos.below()); if (blockstate.getBlock() == ModBlock.HEMLOCK.get()) { if (world.getFluidState(pos.below()).isEmpty() || world.getBlockState(pos.below(2)).getBlock() == ModBlock.HEMLOCK.get()) { world.setBlock(pos.below(), blockstate.setValue(PROPERTY_AGE, 1), 1); } BlockState blockstate1 = world.getBlockState(pos.above()); return blockstate1.getBlock() != ModBlock.HEMLOCK.get() ? ModBlock.HEMLOCK.get().defaultBlockState().setValue(PROPERTY_AGE, 0) : this.defaultBlockState().setValue(PROPERTY_AGE, 1); } if (blockstate.is(ModTags.ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, 0); } else { return null; } } @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState blockstate = context.getLevel().getBlockState(context.getClickedPos().below()); if (blockstate.getBlock() == ModBlock.HEMLOCK.get()) { if (context.getLevel().getFluidState(context.getClickedPos().below()).isEmpty() || context.getLevel().getBlockState(context.getClickedPos().below(2)).getBlock() == ModBlock.HEMLOCK.get()) { context.getLevel().setBlockAndUpdate(context.getClickedPos().below(), blockstate.setValue(PROPERTY_AGE, 1)); } BlockState blockstate1 = context.getLevel().getBlockState(context.getClickedPos().above()); return blockstate1.getBlock() != ModBlock.HEMLOCK.get() ? ModBlock.HEMLOCK.get().defaultBlockState().setValue(PROPERTY_AGE, 0) : this.defaultBlockState().setValue(PROPERTY_AGE, 1); } if (blockstate.is(ModTags.ModBlockTags.REEDS_PLANTABLE_ON)) { return this.defaultBlockState().setValue(PROPERTY_AGE, 0); } else { return null; } } public void tick(BlockState state, ServerLevel worldIn, BlockPos pos, Random rand) { if (!state.canSurvive(worldIn, pos)) { worldIn.destroyBlock(pos, true); } } public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) { return worldIn.getBlockState(pos.below()).is(ModTags.ModBlockTags.REEDS_PLANTABLE_ON) || worldIn.getBlockState(pos.below()).getBlock() == ModBlock.HEMLOCK.get(); } public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) { if (!stateIn.canSurvive(worldIn, currentPos)) { worldIn.scheduleTick(currentPos, this, 1); } return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public boolean isValidBonemealTarget(BlockGetter worldIn, BlockPos pos, BlockState state, boolean isClient) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); return i + j + 1 < 3; } public boolean isBonemealSuccess(Level worldIn, Random rand, BlockPos pos, BlockState state) { return true; } public void performBonemeal(ServerLevel worldIn, Random rand, BlockPos pos, BlockState state) { int i = this.getNumReedBlocksAbove(worldIn, pos); int j = this.getNumReedBlocksBelow(worldIn, pos); int k = i + j + 1; int l = 1 + rand.nextInt(2); for(int i1 = 0; i1 < l; ++i1) { BlockPos blockpos = pos.above(i); BlockState blockstate = worldIn.getBlockState(blockpos); if (k >= 4 || !worldIn.isEmptyBlock(blockpos.above())) { return; } if (blockstate.getValue(PROPERTY_AGE) != 2) { worldIn.setBlock(blockpos, this.defaultBlockState().setValue(PROPERTY_AGE, 1), 3); } worldIn.setBlock(blockpos.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 0), 3); ++i; ++k; } } public float getDestroyProgress(BlockState state, Player player, BlockGetter worldIn, BlockPos pos) { return player.getMainHandItem().canPerformAction(net.minecraftforge.common.ToolActions.SWORD_DIG) ? 1.0F : super.getDestroyProgress(state, player, worldIn, pos); } protected int getNumReedBlocksAbove(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.above(i + 1)).getBlock() == ModBlock.HEMLOCK.get(); ++i) { } return i; } protected int getNumReedBlocksBelow(BlockGetter worldIn, BlockPos pos) { int i; for(i = 0; i < 4 && worldIn.getBlockState(pos.below(i + 1)).getBlock() == ModBlock.HEMLOCK.get(); ++i) { } return i; } public void updatePostGen(LevelAccessor worldIn, BlockPos pos) { if (worldIn.getRandom().nextBoolean()) { worldIn.setBlock(pos, this.defaultBlockState().setValue(PROPERTY_AGE, 1), 3); worldIn.setBlock(pos.above(), this.defaultBlockState().setValue(PROPERTY_AGE, 0), 3); } } }
7,702
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ReptileNestBlockEntity.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/blockentity/ReptileNestBlockEntity.java
package untamedwilds.block.blockentity; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.BlockParticleOption; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import untamedwilds.config.ConfigGamerules; import untamedwilds.config.ConfigMobControl; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.init.ModBlock; import untamedwilds.init.ModEntity; import untamedwilds.util.EntityUtils; import java.util.Random; public class ReptileNestBlockEntity extends BlockEntity { private EntityType<?> entityType = ModEntity.SOFTSHELL_TURTLE.get(); private int variant = 1; private int eggCount = 4; public ReptileNestBlockEntity(BlockPos pos, BlockState state) { super(ModBlock.TILE_ENTITY_NEST_REPTILE.get(), pos, state); } public int getSumMobs() { return this.eggCount; } public boolean hasNoMobs() { return this.getSumMobs() == 0; } public void createMobs(ServerLevel worldIn) { if (!this.hasNoMobs() && this.getEntityType() != null && worldIn.getRandom().nextFloat() < 0.05D) { BlockPos blockpos = this.getBlockPos(); if (worldIn.hasNearbyAlivePlayer((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, ConfigMobControl.critterSpawnRange.get())) { int spawnCount = worldIn.getRandom().nextInt(3) + 1; for(int i = 0; i < spawnCount; ++i) { Random rand = worldIn.getRandom(); float offsetX = rand.nextFloat(); float offsetZ = rand.nextFloat(); if (this.getEggCount() > 0 && this.getEntityType() != null && worldIn.noCollision(this.getEntityType().getAABB(blockpos.getX() + offsetX, blockpos.getY(), blockpos.getZ() + offsetZ).deflate(this.getEntityType().getWidth() / 4).move(0, 4, 0))) { // Turns out that calling EntityType.create(...) will fucking crash the game if it pulls an invalid variant //Entity spawn = this.getEntityType().create(worldIn, null, null, null, blockpos, MobSpawnType.CHUNK_GENERATION, true, false); Entity spawn = this.getEntityType().create(worldIn); if (spawn != null) { spawn.moveTo(blockpos.getX() + offsetX, blockpos.getY(), blockpos.getZ() + offsetZ, Mth.wrapDegrees(rand.nextFloat() * 360.0F), 0.0F); if (spawn instanceof Mob mobSpawn) { mobSpawn.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(blockpos), MobSpawnType.BREEDING, null, null); } if (spawn instanceof ComplexMob entitySpawn) { entitySpawn.setVariant(EntityUtils.getClampedNumberOfSpecies(this.variant, this.entityType)); entitySpawn.setAge(ComplexMob.getEntityData(this.entityType).getGrowingTime(this.variant) * ConfigGamerules.cycleLength.get() * -2); entitySpawn.setBaby(true); entitySpawn.setGender(worldIn.getRandom().nextInt(2)); entitySpawn.setRandomMobSize(); entitySpawn.chooseSkinForSpecies(entitySpawn, true); if (entitySpawn instanceof INeedsPostUpdate) { ((INeedsPostUpdate) entitySpawn).updateAttributes(); } } worldIn.addFreshEntityWithPassengers(spawn); worldIn.playSound(null, this.getBlockPos(), SoundEvents.TURTLE_EGG_BREAK, SoundSource.BLOCKS, 0.7F, 0.9F + worldIn.getRandom().nextFloat() * 0.2F); spawnParticles(worldIn, spawn.getX(), spawn.getY(), spawn.getZ(), new BlockParticleOption(ParticleTypes.BLOCK, Blocks.TURTLE_EGG.defaultBlockState())); removeEggs(worldIn, 1); setChanged(); } } } } } } public void trampleOnNest(Level worldIn, BlockPos posIn, BlockState stateIn) { worldIn.playSound(null, posIn, SoundEvents.TURTLE_EGG_BREAK, SoundSource.BLOCKS, 0.7F, 0.9F + worldIn.random.nextFloat() * 0.2F); removeEggs(worldIn, Math.min(worldIn.getRandom().nextInt(2), this.getEggCount() / 2) + 1); worldIn.levelEvent(2001, posIn, Block.getId(stateIn)); } public void removeEggs(Level worldIn, int count) { this.setEggCount(this.eggCount - count); if (this.eggCount <= 0) { worldIn.destroyBlock(this.getBlockPos(), false); } } public void setEggCount(int newCount) { this.eggCount = newCount; } public int getEggCount() { return this.eggCount; } public void setVariant(int variant) { this.variant = variant; } public int getVariant() { return this.variant; } public void setEntityType(EntityType<?> type) { this.entityType = type; } public EntityType<?> getEntityType() { return this.entityType; } private <T extends ParticleOptions> void spawnParticles(Level worldIn, double x, double y, double z, T particle) { Random random = worldIn.getRandom(); float d3 = random.nextFloat() * 0.02F; float d1 = random.nextFloat() * 0.02F; float d2 = random.nextFloat() * 0.02F; ((ServerLevel)worldIn).sendParticles(particle, x, y, z, 15, d3, d1, d2, 0.12F); } public void load(CompoundTag compound) { super.load(compound); this.setVariant(compound.getInt("Variant")); this.setEggCount(compound.getInt("Count")); if (compound.contains("EntityType")) { this.setEntityType(EntityType.byString(compound.getString("EntityType")).orElse(null)); } } public void saveAdditional(CompoundTag compound) { super.saveAdditional(compound); compound.putInt("Count", this.getEggCount()); compound.putInt("Variant", this.getVariant()); if (this.getEntityType() != null && this.getEntityType().getRegistryName() != null) { compound.putString("EntityType", this.getEntityType().getRegistryName().toString()); } } }
7,097
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CritterBurrowBlockEntity.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/blockentity/CritterBurrowBlockEntity.java
package untamedwilds.block.blockentity; import com.google.common.collect.Lists; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.world.entity.*; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import untamedwilds.config.ConfigMobControl; import untamedwilds.entity.ComplexMob; import untamedwilds.init.ModBlock; import untamedwilds.util.EntityUtils; import java.util.List; public class CritterBurrowBlockEntity extends BlockEntity { private final List<Inhabitants> inhabitants = Lists.newArrayList(); private EntityType<?> entityType; private int variant; private int count; public CritterBurrowBlockEntity(BlockPos pos, BlockState state) { super(ModBlock.TILE_ENTITY_BURROW.get(), pos, state); } public int getSumMobs() { return this.inhabitants.size() + this.count; } public boolean hasNoMobs() { return this.getSumMobs() == 0; } public void tryEnterBurrow(LivingEntity entityIn) { entityIn.stopRiding(); entityIn.ejectPassengers(); CompoundTag CompoundTag = EntityUtils.writeEntityToNBT(entityIn, true); this.inhabitants.add(new Inhabitants(CompoundTag)); if (this.level != null) { BlockPos blockpos = this.getBlockPos(); this.level.playSound(null, blockpos.getX(), blockpos.getY(), blockpos.getZ(), SoundEvents.BEEHIVE_ENTER, SoundSource.BLOCKS, 1.0F, 1.0F); EntityUtils.spawnParticlesOnEntity(this.level, entityIn, ParticleTypes.POOF, 3, 6); } entityIn.remove(Entity.RemovalReason.DISCARDED); setChanged(); } public void releaseOrCreateMob(ServerLevel worldIn) { if (!this.hasNoMobs() && this.getEntityType() != null && this.getVariant() >= 0 && worldIn.getRandom().nextFloat() < 0.1D * (this.getSumMobs() * this.getSumMobs())) { BlockPos blockpos = this.getBlockPos(); if (worldIn.hasNearbyAlivePlayer((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, ConfigMobControl.critterSpawnRange.get())) { if (!this.getInhabitants().isEmpty()) { int i = worldIn.random.nextInt(this.inhabitants.size()); Entity spawn = this.getEntityType().create(worldIn, this.inhabitants.get(i).entityData, null, null, blockpos, MobSpawnType.DISPENSER, true, false); if (spawn != null) { worldIn.addFreshEntityWithPassengers(spawn); this.inhabitants.remove(i); setChanged(); } } else if (this.getCount() > 0 && this.getEntityType() != null) { // Turns out that calling EntityType.create(...) will fucking crash the game if it pulls an invalid variant //Entity spawn = this.getEntityType().create(worldIn, null, null, null, blockpos, MobSpawnType.CHUNK_GENERATION, true, false); Entity spawn = this.getEntityType().create(worldIn); if (spawn != null) { spawn.moveTo(blockpos.getX() + 0.5D, blockpos.getY(), blockpos.getZ() + 0.5D, Mth.wrapDegrees(worldIn.random.nextFloat() * 360.0F), 0.0F); if (spawn instanceof Mob mobSpawn) { mobSpawn.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(blockpos), MobSpawnType.CHUNK_GENERATION, null, null); } if (spawn instanceof ComplexMob entitySpawn) { entitySpawn.setVariant(EntityUtils.getClampedNumberOfSpecies(this.variant, this.entityType)); entitySpawn.setHome(this.getBlockPos()); } worldIn.addFreshEntityWithPassengers(spawn); this.setCount(this.getCount() - 1); setChanged(); } } if (worldIn.getRandom().nextInt(ConfigMobControl.burrowRepopulationChance.get()) == 0 && this.getCount() < 20) { this.setCount(this.getCount() + 1); } } } } public void setCount(int newCount) { this.count = newCount; } public int getCount() { return this.count; } public void setVariant(int variant) { this.variant = variant; } public int getVariant() { return this.variant; } public void setEntityType(EntityType<?> type) { this.entityType = type; } public EntityType<?> getEntityType() { return this.entityType; } public void load(CompoundTag compound) { super.load(compound); this.inhabitants.clear(); ListTag listnbt = compound.getList("Inhabitants", 10); this.setVariant(compound.getInt("Variant")); this.setCount(compound.getInt("Count")); if (compound.contains("entityType")) { this.setEntityType(EntityType.byString(compound.getString("entityType")).orElse(null)); } for(int i = 0; i < listnbt.size(); ++i) { CompoundTag CompoundTag = listnbt.getCompound(i); Inhabitants beehivetileentity$bee = new Inhabitants(CompoundTag.getCompound("EntityData")); this.inhabitants.add(beehivetileentity$bee); } } public void saveAdditional(CompoundTag compound) { super.saveAdditional(compound); compound.put("Inhabitants", this.getInhabitants()); compound.putInt("Count", this.getCount()); compound.putInt("Variant", this.getVariant()); if (this.getEntityType() != null) { compound.putString("entityType", this.getEntityType().getRegistryName().toString()); } } public ListTag getInhabitants() { ListTag inhabitants = new ListTag(); for(Inhabitants inhabitant : this.inhabitants) { CompoundTag CompoundTag = new CompoundTag(); CompoundTag.put("EntityData", inhabitant.entityData); inhabitants.add(CompoundTag); } return inhabitants; } static class Inhabitants { private final CompoundTag entityData; private Inhabitants(CompoundTag nbt) { nbt.remove("UUID"); this.entityData = nbt; } } }
6,671
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
CageBlockEntity.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/blockentity/CageBlockEntity.java
package untamedwilds.block.blockentity; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import untamedwilds.UntamedWilds; import untamedwilds.config.ConfigGamerules; import untamedwilds.init.ModBlock; import untamedwilds.init.ModTags; import untamedwilds.util.EntityUtils; import javax.annotation.Nullable; import java.util.Objects; public class CageBlockEntity extends BlockEntity { private CompoundTag data; private boolean locked; public CageBlockEntity(BlockPos pos, BlockState state) { super(ModBlock.TILE_ENTITY_CAGE.get(), pos, state); } public static boolean isBlacklisted(Entity entity) { return entity.getType().is(ModTags.EntityTags.CAGE_BLACKLIST); } public boolean cageEntity(Mob entity) { if (!this.isLocked()) { if (!isBlacklisted(entity) && (ConfigGamerules.easyMobCapturing.get() || entity.getTarget() == null)) { this.setTagCompound(EntityUtils.writeEntityToNBT(entity)); this.setLocked(true); entity.discard(); setChanged(); return true; } } return false; } public boolean spawnCagedCreature(ServerLevel worldIn, BlockPos pos, boolean offsetHitbox) { if (!worldIn.isClientSide && this.isLocked()) { EntityType<?> entity = EntityUtils.getEntityTypeFromTag(this.getTagCompound(), null); if (entity != null) { if (worldIn.noCollision(entity.getAABB(pos.getX() + 0.5F, pos.getY() - (offsetHitbox ? entity.getHeight() + 1.2F : 0), pos.getZ() + 0.5F))) { if (worldIn.getEntity(this.data.getCompound("EntityTag").getUUID("UUID")) != null) { UntamedWilds.LOGGER.info("UUID is already present in the Level; Randomizing UUID for the new mob"); this.data.getCompound("EntityTag").putUUID("UUID", Mth.createInsecureUUID(worldIn.random)); } Entity caged_entity = entity.create(worldIn, this.data, null, null, pos, MobSpawnType.DISPENSER, true, !Objects.equals(pos, this.getBlockPos())); if (caged_entity != null) { caged_entity.moveTo(pos.getX() + 0.5F, pos.getY() - (offsetHitbox ? caged_entity.getBbHeight() + 1.2 : 0.8), pos.getZ() + 0.5F, Mth.wrapDegrees(worldIn.random.nextFloat() * 360.0F), 0.0F); if (!worldIn.tryAddFreshEntityWithPassengers(caged_entity)) { caged_entity.setUUID(Mth.createInsecureUUID(worldIn.random)); worldIn.addFreshEntityWithPassengers(caged_entity); } this.setTagCompound(null); this.setLocked(true); return true; } } } } return false; } @Nullable public CompoundTag getTagCompound() { return this.data; } private void setTagCompound(@Nullable CompoundTag nbt) { this.data = nbt; } public boolean hasTagCompound() { return this.data != null; } public boolean isLocked() { return this.locked; } private void setLocked(boolean locked) { this.locked = locked; } @Override public void load(CompoundTag compound) { super.load(compound); this.setTagCompound(compound.copy()); this.setLocked(compound.getBoolean("closed")); } @Override public void saveAdditional(CompoundTag compound) { super.saveAdditional(compound); compound.putBoolean("closed", this.isLocked()); if (this.getTagCompound() != null) { compound.put("EntityTag", this.getTagCompound().getCompound("EntityTag")); } } }
4,163
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
EggBlockEntity.java
/FileExtraction/Java_unseen/RayTrace082_untamedwilds/src/main/java/untamedwilds/block/blockentity/EggBlockEntity.java
package untamedwilds.block.blockentity; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.BlockParticleOption; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import untamedwilds.config.ConfigGamerules; import untamedwilds.config.ConfigMobControl; import untamedwilds.entity.ComplexMob; import untamedwilds.entity.INeedsPostUpdate; import untamedwilds.init.ModBlock; import untamedwilds.init.ModEntity; import untamedwilds.util.EntityUtils; import java.util.Random; public class EggBlockEntity extends BlockEntity { private EntityType<?> entityType = ModEntity.SPITTER.get(); private int variant = 0; private boolean canSpawn = true; public EggBlockEntity(BlockPos pos, BlockState state) { super(ModBlock.TILE_ENTITY_EGG.get(), pos, state); } public void releaseOrCreateMob(ServerLevel worldIn) { if (this.getCanSpawn() && this.getEntityType() != null && this.getVariant() >= 0 && worldIn.getRandom().nextFloat() < 0.1D) { BlockPos blockpos = this.getBlockPos(); if (worldIn.hasNearbyAlivePlayer((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, ConfigMobControl.critterSpawnRange.get())) { if (this.getEntityType() != null) { // Turns out that calling EntityType.create(...) will fucking crash the game if it pulls an invalid variant //Entity spawn = this.getEntityType().create(worldIn, null, null, null, blockpos, MobSpawnType.CHUNK_GENERATION, true, false); Entity spawn = this.getEntityType().create(worldIn); if (spawn != null) { spawn.moveTo(blockpos.getX() + 0.5D, blockpos.getY(), blockpos.getZ() + 0.5D, Mth.wrapDegrees(worldIn.random.nextFloat() * 360.0F), 0.0F); if (spawn instanceof Mob mobSpawn) { mobSpawn.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(blockpos), MobSpawnType.BREEDING, null, null); } if (spawn instanceof ComplexMob entitySpawn) { entitySpawn.setVariant(EntityUtils.getClampedNumberOfSpecies(this.variant, this.entityType)); entitySpawn.setAge(ComplexMob.getEntityData(this.entityType).getGrowingTime(this.variant) * ConfigGamerules.cycleLength.get() * -2); entitySpawn.setBaby(true); entitySpawn.setGender(worldIn.getRandom().nextInt(2)); entitySpawn.setRandomMobSize(); entitySpawn.chooseSkinForSpecies(entitySpawn, true); if (entitySpawn instanceof INeedsPostUpdate) { ((INeedsPostUpdate) entitySpawn).updateAttributes(); } } spawnParticles(worldIn, spawn.getX(), spawn.getY(), spawn.getZ(), new BlockParticleOption(ParticleTypes.BLOCK, Blocks.TURTLE_EGG.defaultBlockState())); worldIn.destroyBlock(this.getBlockPos(), false); worldIn.addFreshEntityWithPassengers(spawn); this.setCanSpawn(false); setChanged(); } } } } } public void setCanSpawn(boolean canSpawn) { this.canSpawn = canSpawn; } public boolean getCanSpawn() { return this.canSpawn; } public void setVariant(int variant) { this.variant = variant; } public int getVariant() { return this.variant; } public void setEntityType(EntityType<?> type) { this.entityType = type; } public EntityType<?> getEntityType() { return this.entityType; } private <T extends ParticleOptions> void spawnParticles(Level worldIn, double x, double y, double z, T particle) { Random random = worldIn.getRandom(); float d3 = random.nextFloat() * 0.02F; float d1 = random.nextFloat() * 0.02F; float d2 = random.nextFloat() * 0.02F; ((ServerLevel)worldIn).sendParticles(particle, x, y, z, 15, d3, d1, d2, 0.12F); } public void load(CompoundTag compound) { super.load(compound); this.setVariant(compound.getInt("Variant")); this.setCanSpawn(compound.getBoolean("CanSpawn")); if (compound.contains("entityType")) { this.setEntityType(EntityType.byString(compound.getString("entityType")).orElse(null)); } } public void saveAdditional(CompoundTag compound) { super.saveAdditional(compound); compound.putBoolean("CanSpawn", this.getCanSpawn()); compound.putInt("Variant", this.getVariant()); if (this.getEntityType() != null) { compound.putString("entityType", this.getEntityType().getRegistryName().toString()); } } }
5,495
Java
.java
RayTrace082/untamedwilds
13
11
79
2020-07-25T21:16:24Z
2024-05-06T16:27:45Z
ChineseMobileNumberGeneratorTest.java
/FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/ChineseMobileNumberGeneratorTest.java
package cn.binarywang.tools.generator; import static org.testng.AssertJUnit.assertNotNull; import org.testng.annotations.Test; @Test public class ChineseMobileNumberGeneratorTest { public void testGenerate() { String generatedMobileNum = ChineseMobileNumberGenerator.getInstance() .generate(); assertNotNull(generatedMobileNum); System.err.println(generatedMobileNum); } public void testGgenerateFake() { String generatedMobileNum = ChineseMobileNumberGenerator.getInstance() .generateFake(); assertNotNull(generatedMobileNum); System.err.println(generatedMobileNum); } }
665
Java
.java
binarywang/java-testdata-generator
584
276
0
2016-01-21T05:45:44Z
2023-06-21T06:48:09Z