diff --git a/src/main/java/mekanism/client/ClientProxy.java b/src/main/java/mekanism/client/ClientProxy.java index 48e41da76..0e77e68c1 100644 --- a/src/main/java/mekanism/client/ClientProxy.java +++ b/src/main/java/mekanism/client/ClientProxy.java @@ -101,6 +101,7 @@ import mekanism.client.render.transmitter.RenderMechanicalPipe; import mekanism.client.render.transmitter.RenderPressurizedTube; import mekanism.client.render.transmitter.RenderThermodynamicConductor; import mekanism.client.render.transmitter.RenderUniversalCable; +import mekanism.client.sound.SoundHandler; import mekanism.common.CommonProxy; import mekanism.common.Mekanism; import mekanism.common.MekanismBlocks; @@ -1035,6 +1036,7 @@ public class ClientProxy extends CommonProxy MinecraftForge.EVENT_BUS.register(new ClientPlayerTracker()); MinecraftForge.EVENT_BUS.register(new ClientTickHandler()); MinecraftForge.EVENT_BUS.register(new RenderTickHandler()); + MinecraftForge.EVENT_BUS.register(SoundHandler.class); new MekanismKeyHandler(); diff --git a/src/main/java/mekanism/client/ClientTickHandler.java b/src/main/java/mekanism/client/ClientTickHandler.java index 0b9ad0b19..7c4c99bfb 100644 --- a/src/main/java/mekanism/client/ClientTickHandler.java +++ b/src/main/java/mekanism/client/ClientTickHandler.java @@ -203,9 +203,9 @@ public class ClientTickHandler // Update player's state for various items; this also automatically notifies server if something changed and // kicks off sounds as necessary - Mekanism.playerState.setJetpackState(mc.player.getName(), isJetpackActive(mc.player)); - Mekanism.playerState.setGasmaskState(mc.player.getName(), isGasMaskOn(mc.player)); - Mekanism.playerState.setFlamethrowerState(mc.player.getName(), isFlamethrowerOn(mc.player)); + Mekanism.playerState.setJetpackState(mc.player.getName(), isJetpackActive(mc.player), true); + Mekanism.playerState.setGasmaskState(mc.player.getName(), isGasMaskOn(mc.player), true); + Mekanism.playerState.setFlamethrowerState(mc.player.getName(), isFlamethrowerOn(mc.player), true); for(Iterator> iter = portableTeleports.entrySet().iterator(); iter.hasNext();) { diff --git a/src/main/java/mekanism/client/sound/PlayerSound.java b/src/main/java/mekanism/client/sound/PlayerSound.java index 2aae08097..51dec86fd 100644 --- a/src/main/java/mekanism/client/sound/PlayerSound.java +++ b/src/main/java/mekanism/client/sound/PlayerSound.java @@ -1,5 +1,6 @@ package mekanism.client.sound; +import mekanism.common.Mekanism; import net.minecraft.client.audio.ITickableSound; import net.minecraft.client.audio.MovingSound; import net.minecraft.client.audio.PositionedSound; @@ -23,6 +24,8 @@ public abstract class PlayerSound extends PositionedSound implements ITickableSo public PlayerSound(EntityPlayer player, ResourceLocation sound) { super(sound, SoundCategory.PLAYERS); this.player = player; + this.repeat = true; + this.repeatDelay = 0; // N.B. the volume must be > 0 on first time it's processed by sound system or else it will not // get registered for tick events. diff --git a/src/main/java/mekanism/client/sound/SoundHandler.java b/src/main/java/mekanism/client/sound/SoundHandler.java index faebe4d33..2e7ad781a 100644 --- a/src/main/java/mekanism/client/sound/SoundHandler.java +++ b/src/main/java/mekanism/client/sound/SoundHandler.java @@ -1,30 +1,54 @@ package mekanism.client.sound; import mekanism.common.Mekanism; +import mekanism.common.Upgrade; +import mekanism.common.base.IUpgradeTile; import mekanism.common.config.MekanismConfig; import net.minecraft.client.Minecraft; -import net.minecraft.client.audio.ISound; -import net.minecraft.client.audio.PositionedSoundRecord; +import net.minecraft.client.audio.*; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.client.ForgeHooksClient; +import net.minecraftforge.client.event.sound.PlaySoundEvent; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import javax.annotation.Nullable; +import java.util.HashMap; import java.util.IdentityHashMap; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; -// SoundHandler is the central point for sounds on Mek client side. Some sounds, such as hand-held items -// are instantiated the first time user uses one and stays in memory (though muted) until the player -// leaves the server. Block/tile-based sounds are periodically restarted while machine is active; this ensures -// that thousands of idle machines aren't filling up memory with sounds that are rarely running. +// SoundHandler is the central point for sounds on Mek client side. There are roughly three classes of sounds to deal +// with: +// 1. One-shot sounds like GUI interactions; play the sound and done // -// As of 1.12.2, this design closely mirrors that of Minecraft sounds and should be generally compatible with any -// other mod that interacts with the sound system (such as mufflers) +// 2. Long-lived player item sounds (such as jetpacks): long-running sounds that may flip on/off quickly based +// on user action. We follow the minecart model for these sounds; starting a sound and then muting when not in use. +// +// 3. Tile entity sounds: long-running, repeating sounds that run while a fixed tile is active. These are sounds that +// users want to be able to mute effectively. +// +// All sounds, when initially started can be intercepted on the Forge event bus and wrapped by various muting/manipulation +// mods. For item sounds, we don't want to them to be manipulated, since the flipping on/off is too prone to weird timing +// issues. For long-running sounds, we need a way to honor these attempted manipulations, without allowing them to become +// the permanent state of the sound (which is what happens by default). To accomplish this, we have our own wrapper that +// intercepts new repeating sounds from Mek and ensures that they periodically poll for any muting/manipulation so that +// it the object can dynamically adjust to conditions. @SideOnly(Side.CLIENT) public class SoundHandler { private static IdentityHashMap jetpackSounds = new IdentityHashMap(); private static IdentityHashMap gasmaskSounds = new IdentityHashMap<>(); + private static Map soundMap = new HashMap<>(); + public static void startSound(EntityPlayer player, String soundName) { ISound soundToPlay = null; @@ -38,18 +62,217 @@ public class SoundHandler { } if (soundToPlay != null) { - Mekanism.logger.info("Starting sound object for {}: {}", player.getName(), soundName); Minecraft.getMinecraft().getSoundHandler().playSound(soundToPlay); } } - public static void playSound(SoundEvent sound) - { + public static void playSound(SoundEvent sound) { playSound(PositionedSoundRecord.getMasterRecord(sound, MekanismConfig.client.baseSoundVolume)); } - public static void playSound(ISound sound) - { + public static void playSound(ISound sound) { Minecraft.getMinecraft().getSoundHandler().playSound(sound); } + + public static ISound startTileSound(ResourceLocation soundLoc, float volume, BlockPos pos) { + // First, check to see if there's already a sound playing at the desired location + ISound s = soundMap.get(pos.toLong()); + if (s == null || !Minecraft.getMinecraft().getSoundHandler().isSoundPlaying(s)) { + // No sound playing, start one up - we assume that tile sounds will play until explicitly stopped + s = new PositionedSoundRecord(soundLoc, SoundCategory.BLOCKS, volume, 1.0f, + true, 0, ISound.AttenuationType.LINEAR, + pos.getX() + 0.5f, pos.getY() + 0.5f, pos.getZ() + 0.5f); + + // Force the underlying sound to get initialized + // TODO: Understand what this is doing exactly + s.createAccessor(Minecraft.getMinecraft().getSoundHandler()); + + // Start the sound + playSound(s); + + // N.B. By the time playSound returns, our expectation is that our wrapping-detector handler has fired + // and dealt with any muting interceptions and, CRITICALLY, updated the soundMap with the final ISound. + s = soundMap.get(pos.toLong()); + } + + return s; + } + + public static void stopTileSound(BlockPos pos) { + long posKey = pos.toLong(); + ISound s = soundMap.get(posKey); + if (s != null) { + // TODO: Saw some code that suggests there is a soundmap MC already tracks; investigate further + // and maybe we can avoid this dedicated soundmap + Minecraft.getMinecraft().getSoundHandler().stopSound(s); + soundMap.remove(posKey); + } + } + + private static boolean IN_MUFFLED_CHECK = false; + + @SubscribeEvent(priority = EventPriority.LOWEST) + public static void onTilePlaySound(PlaySoundEvent event) { + // Ignore any sound event which is null or is happening in a muffled check + ISound resultSound = event.getResultSound(); + if (resultSound == null || IN_MUFFLED_CHECK) { + return; + } + + // Ignore any sound event outside this mod namespace + ResourceLocation soundLoc = event.getSound().getSoundLocation(); + if (!soundLoc.getNamespace().equals("mekanism")) { + return; + } + + // Ignore any Mek sounds that aren't either a player or block event + SoundCategory category = event.getSound().getCategory(); + if (!category.equals(SoundCategory.PLAYERS) && !category.equals(SoundCategory.BLOCKS)) { + return; + } + + // If this is a Mek player sound, unwrap any muffling that other mods may have attempted. I haven't + // sorted out a good way to deal with long-lived, non-repeating, dynamic volume sounds -- something + // to investigate in the future. + if (event.getSound() instanceof PlayerSound) { + event.setResultSound(event.getSound()); + return; + } + + // At this point, we've got a known block Mekanism sound. We want to re-wrap the original + // using the (possibly) muffled sound as the initial volume. The TileSound will then periodically poll + // to see if the volume should be adjusted + resultSound = new TileSound(event.getSound(), resultSound.getVolume()); + event.setResultSound(resultSound); + + + // Finally, update our soundMap so that we can actually have a shot at stopping this sound; note that we also + // need to "unoffset" the sound position so that we build the correct key for the sound map + // Aside: I really, really, wish Forge returned the final result sound as part of playSound :/ + BlockPos pos = new BlockPos(resultSound.getXPosF() - 0.5f, resultSound.getYPosF() - 0.5f, resultSound.getZPosF() -0.5); + soundMap.put(pos.toLong(), resultSound); + } + + private static class TileSound implements ITickableSound { + + private ISound original; + private float volume; + private boolean donePlaying = false; + + // Choose an interval between 60-80 ticks (3-4 seconds) to check for muffling changes. We do this + // to ensure that not every tile sound tries to run on the same tick and thus create + // uneven spikes of CPU usage + private int checkInterval = 60 + ThreadLocalRandom.current().nextInt(20); + + private Minecraft mc = Minecraft.getMinecraft(); + + TileSound(ISound original, float volume) { + this.original = original; + this.volume = volume; + } + + @Override + public void update() { + // Every configured interval, see if we need to adjust muffling + if (mc.world.getTotalWorldTime() % checkInterval == 0) { + + // Run the event bus with the original sound. Note that we must making sure to set the GLOBAL/STATIC + // flag that ensures we don't wrap already muffled sounds. This is...NOT ideal and makes some + // significant (hopefully well-informed) assumptions about locking/ordering of all these calls. + IN_MUFFLED_CHECK = true; + ISound s = ForgeHooksClient.playSound(mc.getSoundHandler().sndManager, original); + IN_MUFFLED_CHECK = false; + + if (s == this) { + // No filtering done, use the original sound's volume + volume = original.getVolume() * getMufflingFactor(); + } else if (s == null){ + // Full on mute; go ahead and shutdown + donePlaying = true; + } else { + // Altered sound returned; adjust volume + volume = s.getVolume() * getMufflingFactor(); + } + } + } + + private float getMufflingFactor() { + // Pull the TE from the sound position and see if supports muffling upgrades. If it does, calculate what + // percentage of the original volume should be muted + TileEntity te = mc.world.getTileEntity(new BlockPos(original.getXPosF(), original.getYPosF(), original.getZPosF())); + if (te != null && te instanceof IUpgradeTile && ((IUpgradeTile) te).getComponent().supports(Upgrade.MUFFLING)) { + int mufflerCount = ((IUpgradeTile) te).getComponent().getUpgrades(Upgrade.MUFFLING); + return Math.max(0.001f, 1.0f - (mufflerCount / (float)Upgrade.MUFFLING.getMax())); + } + return 0; + } + + @Override + public boolean isDonePlaying() { + return donePlaying; + } + + @Override + public float getVolume() { + return volume; + } + + @Override + public ResourceLocation getSoundLocation() { + return original.getSoundLocation(); + } + + @Nullable + @Override + public SoundEventAccessor createAccessor(net.minecraft.client.audio.SoundHandler handler) { + return original.createAccessor(handler); + } + + @Override + public Sound getSound() { + return original.getSound(); + } + + @Override + public SoundCategory getCategory() { + return original.getCategory(); + } + + @Override + public boolean canRepeat() { + return original.canRepeat(); + } + + @Override + public int getRepeatDelay() { + return original.getRepeatDelay(); + } + + @Override + public float getPitch() { + return original.getPitch(); + } + + @Override + public float getXPosF() { + return original.getXPosF(); + } + + @Override + public float getYPosF() { + return original.getYPosF(); + } + + @Override + public float getZPosF() { + return original.getZPosF(); + } + + @Override + public AttenuationType getAttenuationType() { + return original.getAttenuationType(); + } + + + } } diff --git a/src/main/java/mekanism/client/sound/TileSound.java b/src/main/java/mekanism/client/sound/TileSound.java new file mode 100644 index 000000000..309fe0bf1 --- /dev/null +++ b/src/main/java/mekanism/client/sound/TileSound.java @@ -0,0 +1,4 @@ +package mekanism.client.sound; + +public class TileSound { +} diff --git a/src/main/java/mekanism/common/PlayerState.java b/src/main/java/mekanism/common/PlayerState.java index 499b05665..748f5f895 100644 --- a/src/main/java/mekanism/common/PlayerState.java +++ b/src/main/java/mekanism/common/PlayerState.java @@ -40,33 +40,30 @@ public class PlayerState { } - @SideOnly(Side.CLIENT) - private boolean isLocalPlayer(String playerId) { - return Minecraft.getMinecraft().player.getName().equals(playerId); - } - // ---------------------- // // Jetpack state tracking // // ---------------------- - public void setJetpackState(String playerId, boolean isActive) { + public void setJetpackState(String playerId, boolean isActive, boolean isLocal) { boolean alreadyActive = activeJetpacks.contains(playerId); boolean changed = (alreadyActive != isActive); if (alreadyActive && !isActive) { // On -> off + Mekanism.logger.info("{} jetpack is now off", playerId); activeJetpacks.remove(playerId); } else if (!alreadyActive && isActive) { // Off -> on + Mekanism.logger.info("{} jetpack is now on", playerId); activeJetpacks.add(playerId); } // If something changed and we're in a remote world, take appropriate action if (changed && world.isRemote) { // If the player is the "local" player, we need to tell the server the state has changed - if (isLocalPlayer(playerId)) { + if (isLocal) { Mekanism.packetHandler.sendToServer(PacketJetpackData.JetpackDataMessage.UPDATE(playerId, isActive)); } @@ -79,7 +76,7 @@ public class PlayerState { public void setActiveJetpacks(Set newActiveJetpacks) { for (String activeUser: newActiveJetpacks) { - setJetpackState(activeUser, true); + setJetpackState(activeUser, true, false); } } @@ -97,7 +94,7 @@ public class PlayerState { // // ---------------------- - public void setGasmaskState(String playerId, boolean isActive) { + public void setGasmaskState(String playerId, boolean isActive, boolean isLocal) { boolean alreadyActive = activeGasmasks.contains(playerId); boolean changed = (alreadyActive != isActive); @@ -110,7 +107,7 @@ public class PlayerState { // If something changed and we're in a remote world, take appropriate action if (changed && world.isRemote) { // If the player is the "local" player, we need to tell the server the state has changed - if (isLocalPlayer(playerId)) { + if (isLocal) { Mekanism.packetHandler.sendToServer(PacketScubaTankData.ScubaTankDataMessage.UPDATE(playerId, isActive)); } @@ -123,7 +120,7 @@ public class PlayerState { public void setActiveGasmasks(Set newActiveGasmasks) { for (String activeUser: newActiveGasmasks) { - setGasmaskState(activeUser, true); + setGasmaskState(activeUser, true, false); } } @@ -141,7 +138,7 @@ public class PlayerState { // // ---------------------- - public void setFlamethrowerState(String playerId, boolean isActive) { + public void setFlamethrowerState(String playerId, boolean isActive, boolean isLocal) { boolean alreadyActive = activeFlamethrowers.contains(playerId); boolean changed = (alreadyActive != isActive); @@ -154,7 +151,7 @@ public class PlayerState { // If something changed and we're in a remote world, take appropriate action if (changed && world.isRemote) { // If the player is the "local" player, we need to tell the server the state has changed - if (isLocalPlayer(playerId)) { + if (isLocal) { Mekanism.packetHandler.sendToServer(new FlamethrowerDataMessage(FlamethrowerPacket.UPDATE, null, playerId, isActive)); } diff --git a/src/main/java/mekanism/common/network/PacketFlamethrowerData.java b/src/main/java/mekanism/common/network/PacketFlamethrowerData.java index 1726e87c7..000f0091b 100644 --- a/src/main/java/mekanism/common/network/PacketFlamethrowerData.java +++ b/src/main/java/mekanism/common/network/PacketFlamethrowerData.java @@ -20,7 +20,7 @@ public class PacketFlamethrowerData implements IMessageHandler @Override @SideOnly(Side.CLIENT) - public float getVolume() + public float getInitialVolume() { - return 0.5F*super.getVolume(); + return 0.5F*super.getInitialVolume(); } } diff --git a/src/main/java/mekanism/common/tile/TileEntityEnrichmentChamber.java b/src/main/java/mekanism/common/tile/TileEntityEnrichmentChamber.java index 6ede8a3b3..4edcd50fe 100644 --- a/src/main/java/mekanism/common/tile/TileEntityEnrichmentChamber.java +++ b/src/main/java/mekanism/common/tile/TileEntityEnrichmentChamber.java @@ -26,8 +26,8 @@ public class TileEntityEnrichmentChamber extends TileEntityElectricMachine 0) { + return; + } + + if (activeSound == null || !Minecraft.getMinecraft().getSoundHandler().isSoundPlaying(activeSound)) { + activeSound = SoundHandler.startTileSound(soundEvent.getSoundName(), getInitialVolume(), getPos()); + playSoundCooldown = 20; } } else { - // Not active; stop any active playing sounds - if (activeSound != null && mc.getSoundHandler().isSoundPlaying(activeSound)) { - mc.getSoundHandler().stopSound(activeSound); + if (activeSound != null) { + SoundHandler.stopTileSound(getPos()); activeSound = null; + playSoundCooldown = 0; } } } + @Override + public void invalidate() { + super.invalidate(); + + if (world.isRemote) { + updateSound(); + } + } @Override public void onUpdate() diff --git a/src/main/java/mekanism/generators/common/tile/TileEntitySolarGenerator.java b/src/main/java/mekanism/generators/common/tile/TileEntitySolarGenerator.java index 1a56faf16..311281f98 100644 --- a/src/main/java/mekanism/generators/common/tile/TileEntitySolarGenerator.java +++ b/src/main/java/mekanism/generators/common/tile/TileEntitySolarGenerator.java @@ -43,9 +43,9 @@ public class TileEntitySolarGenerator extends TileEntityGenerator @Override @SideOnly(Side.CLIENT) - public float getVolume() + public float getInitialVolume() { - return 0.05F*super.getVolume(); + return 0.05F*super.getInitialVolume(); } @Override diff --git a/src/main/java/mekanism/generators/common/tile/TileEntityWindGenerator.java b/src/main/java/mekanism/generators/common/tile/TileEntityWindGenerator.java index 8f00954aa..2a9fab5bb 100644 --- a/src/main/java/mekanism/generators/common/tile/TileEntityWindGenerator.java +++ b/src/main/java/mekanism/generators/common/tile/TileEntityWindGenerator.java @@ -11,8 +11,6 @@ import mekanism.common.util.MekanismUtils; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; public class TileEntityWindGenerator extends TileEntityGenerator implements IBoundingBlock { @@ -102,9 +100,9 @@ public class TileEntityWindGenerator extends TileEntityGenerator implements IBou } @Override - protected float getVolume() + protected float getInitialVolume() { - return 1.5F*super.getVolume(); + return 1.5F*super.getInitialVolume(); } private static final String[] methods = new String[] {"getEnergy", "getOutput", "getMaxEnergy", "getEnergyNeeded", "getMultiplier"}; diff --git a/src/main/java/mekanism/generators/common/tile/reactor/TileEntityReactorController.java b/src/main/java/mekanism/generators/common/tile/reactor/TileEntityReactorController.java index 35701c5fd..edae96df4 100644 --- a/src/main/java/mekanism/generators/common/tile/reactor/TileEntityReactorController.java +++ b/src/main/java/mekanism/generators/common/tile/reactor/TileEntityReactorController.java @@ -5,6 +5,7 @@ import io.netty.buffer.ByteBuf; import mekanism.api.Coord4D; import mekanism.api.gas.GasStack; import mekanism.api.gas.GasTank; +import mekanism.client.sound.SoundHandler; import mekanism.common.Mekanism; import mekanism.common.MekanismFluids; import mekanism.common.base.IActiveState; @@ -50,6 +51,7 @@ public class TileEntityReactorController extends TileEntityReactorBlock implemen @SideOnly(Side.CLIENT) private ISound activeSound; + private int playSoundCooldown = 0; public double clientTemp = 0; public boolean clientBurning = false; @@ -122,22 +124,36 @@ public class TileEntityReactorController extends TileEntityReactorBlock implemen @SideOnly(Side.CLIENT) private void updateSound() { - Minecraft mc = Minecraft.getMinecraft(); - if (isBurning() && !isInvalid()) { - // Machine is active; if we don't have a sound already playing, schedule another - if (activeSound == null || !mc.getSoundHandler().isSoundPlaying(activeSound)) { - activeSound = new PositionedSoundRecord(soundEvent, SoundCategory.BLOCKS, 2.0f, 1.0f, getPos()); - mc.getSoundHandler().playSound(activeSound); - } - } else { - // Not active; stop any active playing sounds - if (activeSound != null && mc.getSoundHandler().isSoundPlaying(activeSound)) { - mc.getSoundHandler().stopSound(activeSound); - activeSound = null; - } - } + if (getActive() && !isInvalid()) { + // If sounds are being muted, we can attempt to start them on every tick, only to have them + // denied by the event bus, so use a cooldown period that ensures we're only trying once every + // second or so to start a sound. + if (--playSoundCooldown > 0) { + return; + } + + if (activeSound == null || !Minecraft.getMinecraft().getSoundHandler().isSoundPlaying(activeSound)) { + activeSound = SoundHandler.startTileSound(soundEvent.getSoundName(), 1.0f, getPos()); + playSoundCooldown = 20; + } + } else { + if (activeSound != null) { + SoundHandler.stopTileSound(getPos()); + activeSound = null; + playSoundCooldown = 0; + } + } } + @Override + public void invalidate() { + super.invalidate(); + + if (world.isRemote) { + updateSound(); + } + } + @Override public void onChunkUnload() {