Skip to content

Commit

Permalink
fix double Instance Server class and system clean on class Entity and…
Browse files Browse the repository at this point in the history
… SculkServerSession for remove player on list only player
  • Loading branch information
SenseiTarzan committed Dec 24, 2024
1 parent b884ae8 commit 64fa62e
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 38 deletions.
32 changes: 11 additions & 21 deletions src/main/java/org/sculk/Sculk.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.sculk.config.ServerProperties;
import org.sculk.lang.LanguageKeys;
import org.sculk.lang.LocalManager;
import org.sculk.network.protocol.ProtocolInfo;
Expand All @@ -12,6 +13,7 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

Expand Down Expand Up @@ -46,34 +48,22 @@ public class Sculk {
private static final String LOG_LANGUAGE_NOT_FOUND = "Language code {} not found, defaulting to en_GB";

public static void main(String[] args) {
Thread.currentThread().setName("sculkmp-main");
System.setProperty("log4j.skipJansi", "false");
Logger log = LogManager.getLogger(Sculk.class);

LocalManager localManager = new LocalManager(Sculk.class.getClassLoader(), "language");
try {
Properties properties = loadServerProperties();
String langCode = properties.getProperty("language", LANGUAGE_DEFAULT);

var language = localManager.getLanguage(langCode);
if (language == null) {
log.warn(LOG_LANGUAGE_NOT_FOUND, langCode);
language = localManager.getLanguage(LANGUAGE_DEFAULT);
}

new Server(localManager, log, DATA_PATH);
} catch (Exception e) {
log.throwing(e);
shutdown();
}

int javaVersion = getJavaVersion();
if (javaVersion < 21) {
log.error(LOG_UNSUPPORTED_JAVA, TextFormat.RED, javaVersion);
LogManager.shutdown();
return;
}
Thread.currentThread().setName("sculkmp-main");
System.setProperty("log4j.skipJansi", "false");

Logger log = LogManager.getLogger(Sculk.class);

LocalManager localManager = new LocalManager(Sculk.class.getClassLoader(), "language");
if (!(new File(DATA_PATH + "server.properties").exists())) {

new ServerProperties(Path.of(DATA_PATH));
}
try {
new Server(localManager, log, DATA_PATH);
} catch (Exception e) {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/sculk/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,10 @@ public void start() {
}

public void shutdown() {
Map<UUID, Player> onlinePlayers = this.getOnlinePlayers();
if (this.shutdown) {
return;
}
Map<UUID, Player> onlinePlayers = this.getOnlinePlayers();
for (Map.Entry<UUID, Player> entry : onlinePlayers.entrySet()) {
Player player = entry.getValue();
player.getNetworkSession().disconnect(SERVER_CLOSED_MESSAGE);
Expand All @@ -225,6 +225,7 @@ public void shutdown() {
this.console.getConsoleThread().interrupt();

this.logger.info(this.language.translate(LanguageKeys.SCULK_THREADS_STOPPING));
System.exit(0);
}

public CompletableFuture<Player> createPlayer(SculkServerSession session, ClientChainData info, boolean authenticated) {
Expand Down
21 changes: 15 additions & 6 deletions src/main/java/org/sculk/entity/Entity.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@
import org.sculk.player.Player;

import javax.annotation.Nullable;
import java.lang.ref.Cleaner;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*
* ____ _ _
Expand All @@ -39,7 +43,7 @@
* @author: SculkTeams
* @link: http://www.sculkmp.org/
*/
public abstract class Entity {
public abstract class Entity implements Cleaner.Cleanable {

private static long nextEntityId = 1;

Expand All @@ -50,7 +54,7 @@ public static long getNextEntityId() {

public abstract String getNetworkTypeId();

protected List<Player> hasSpawned;
protected Set<Player> hasSpawned;
@Getter
private long entityId;
protected Server server;
Expand Down Expand Up @@ -109,7 +113,7 @@ public Entity() {
networkPropertiesDirty = true;
this.size = this.getInitialSizeInfo();
this.ownerId = null;
this.hasSpawned = new ObjectArrayList<Player>();
this.hasSpawned = new HashSet<>();
this.initEntity(NbtMap.EMPTY);
}
public Entity(NbtMap nbt) {
Expand All @@ -122,7 +126,7 @@ public Entity(NbtMap nbt) {
networkPropertiesDirty = true;
this.size = this.getInitialSizeInfo();
this.ownerId = null;
this.hasSpawned = new ObjectArrayList<Player>();
this.hasSpawned = new HashSet<>();
this.initEntity(nbt);
}

Expand Down Expand Up @@ -203,7 +207,7 @@ public boolean onUpdate(long currentTick) {
return (hasUpdate);
}

public List<Player> getViewers()
public Set<Player> getViewers()
{
return this.hasSpawned;
}
Expand Down Expand Up @@ -303,7 +307,7 @@ public void spawnTo(Player player) {
}

public void respawnToAll() {
List<Player> players = this.getViewers();
Set<Player> players = this.getViewers();
this.hasSpawned.clear();
for (Player player : players) {
this.spawnTo(player);
Expand Down Expand Up @@ -370,4 +374,9 @@ public void sendData(EntityDataMap data) {
//TODO: add system viewer
NetworkBroadcastUtils.broadcastEntityEvent(List.of(), (EntityEventBroadcaster broadcaster, List<SculkServerSession> recipients) -> broadcaster.syncActorData(recipients, this, data));
}

@Override
public void clean() {
this.despawnFromAll();
}
}
6 changes: 3 additions & 3 deletions src/main/java/org/sculk/network/BedrockInterface.java
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ public void setName(String name) {
.ipv4Port(19132)
.ipv6Port(19132);

for (Channel channel : this.serverChannels) {
for (RakServerChannel channel : this.serverChannels) {
channel.config().setOption(RakChannelOption.RAK_ADVERTISEMENT, this.bedrockPong.toByteBuf());
}
}
Expand All @@ -193,8 +193,8 @@ public boolean process() {

@Override
public void shutdown() {
for(Channel channel : this.serverChannels) {
channel.closeFuture().awaitUninterruptibly();
for(RakServerChannel channel : this.serverChannels) {
channel.close();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.cloudburstmc.protocol.bedrock.data.entity.EntityDataMap;
import org.cloudburstmc.protocol.bedrock.packet.BedrockPacket;
import org.cloudburstmc.protocol.bedrock.packet.RemoveEntityPacket;
import org.cloudburstmc.protocol.bedrock.packet.SetEntityDataPacket;
import org.sculk.entity.Attribute;
import org.sculk.entity.Entity;
Expand Down Expand Up @@ -39,7 +40,9 @@ public void syncActorData(List<SculkServerSession> recipients, Entity entity, En

public void onEntityRemoved(List<SculkServerSession> recipients, Entity entity)
{
//TODO
RemoveEntityPacket packet = new RemoveEntityPacket();
packet.setUniqueEntityId(entity.getEntityId());
this.sendDataPacket(recipients, packet);
}


Expand Down
10 changes: 10 additions & 0 deletions src/main/java/org/sculk/network/session/SculkPeer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import org.cloudburstmc.protocol.bedrock.BedrockPeer;
import org.cloudburstmc.protocol.bedrock.BedrockSession;
import org.cloudburstmc.protocol.bedrock.BedrockSessionFactory;
import org.cloudburstmc.protocol.bedrock.netty.BedrockPacketWrapper;
import org.cloudburstmc.protocol.bedrock.packet.BedrockPacket;
Expand All @@ -15,6 +16,15 @@ public class SculkPeer extends BedrockPeer {
public SculkPeer(Channel channel, BedrockSessionFactory sessionFactory) {
super(channel, sessionFactory);
}

@Override
protected void removeSession(BedrockSession session) {
super.removeSession(session);
if (session instanceof SculkServerSession sculkServerSession) {
sculkServerSession.clean();
}
}

public void sendPacket(int senderClientId, int targetClientId, List<BedrockPacket> packets) {
packets.forEach(packet -> {
super.sendPacket(senderClientId, targetClientId, packet);
Expand Down
12 changes: 11 additions & 1 deletion src/main/java/org/sculk/network/session/SculkServerSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.sculk.utils.SkinUtils;

import javax.annotation.Nullable;
import java.lang.ref.Cleaner;
import java.util.List;
import java.util.Map;
import java.util.Objects;
Expand All @@ -41,7 +42,7 @@
* @link: http://www.sculkmp.org/
*/
@Getter
public class SculkServerSession extends BedrockServerSession {
public class SculkServerSession extends BedrockServerSession implements Cleaner.Cleanable {

private final Server server;
private final BedrockInterface bedrockInterface;
Expand Down Expand Up @@ -185,6 +186,7 @@ public void onPlayerAdded(Player p){
public void onPlayerRemoved(Player p) {
if(!p.equals(this.player)){
PlayerListPacket packet = new PlayerListPacket();
packet.setAction(PlayerListPacket.Action.REMOVE);
packet.getEntries().add(this.createPlayerEntry(p, false));
this.sendPacket(packet);
}
Expand Down Expand Up @@ -302,4 +304,12 @@ public void onMessageSystem(String message) {
packet.setMessage(message);
this.sendPacket(packet);
}

@Override
public void clean() {
if (this.player != null) {
this.player.clean();
this.player = null;
}
}
}
43 changes: 39 additions & 4 deletions src/main/java/org/sculk/network/utils/NetworkBroadcastUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
import org.sculk.network.session.SculkServerSession;
import org.sculk.player.Player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.function.BiConsumer;

public class NetworkBroadcastUtils {
Expand Down Expand Up @@ -38,6 +35,24 @@ public static void broadcastEntityEvent(List<Player> recipients, BiConsumer<Enti
broadcasterTargets.forEach(callback);
}

public static void broadcastEntityEvent(Set<Player> recipients, BiConsumer<EntityEventBroadcaster, List<SculkServerSession>> callback) {
// Group broadcasters and their associated sessions
Map<EntityEventBroadcaster, List<SculkServerSession>> broadcasterTargets = new HashMap<>();

for (Player recipient : recipients) {
SculkServerSession session = recipient.getNetworkSession();
EntityEventBroadcaster broadcaster = session.getEntityEventBroadcaster();

// Group sessions by broadcaster
broadcasterTargets
.computeIfAbsent(broadcaster, k -> new ArrayList<>())
.add(session);
}

// Invoke callback for each unique broadcaster
broadcasterTargets.forEach(callback);
}


public static void broadcastPackets(List<Player> recipients, List<BedrockPacket> packets) {
// Group broadcasters and their associated sessions
Expand All @@ -58,4 +73,24 @@ public static void broadcastPackets(List<Player> recipients, List<BedrockPacket>
broadcaster.broadcastPackets(sculkServerSessions, packets);
});
}

public static void broadcastPackets(Set<Player> recipients, List<BedrockPacket> packets) {
// Group broadcasters and their associated sessions
Map<PacketBroadcaster, List<SculkServerSession>> broadcasterTargets = new HashMap<>();

for (Player recipient : recipients) {
SculkServerSession session = recipient.getNetworkSession();
PacketBroadcaster broadcaster = session.getBroadcaster();

// Group sessions by broadcaster
broadcasterTargets
.computeIfAbsent(broadcaster, k -> new ArrayList<>())
.add(session);
}

// Invoke callback for each unique broadcaster
broadcasterTargets.forEach((broadcaster, sculkServerSessions) -> {
broadcaster.broadcastPackets(sculkServerSessions, packets);
});
}
}
8 changes: 7 additions & 1 deletion src/main/java/org/sculk/player/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ public boolean onUpdate(long currentTick) {

@Override
public void spawnTo(@NonNull Player player) {
if (this.isAlive() && player.isAlive()) {
if (this.isAlive() && player.isAlive() && this.canSee(player)) {
super.spawnTo(player);
}
}
Expand Down Expand Up @@ -390,4 +390,10 @@ public void sendWhisper(RawTextBuilder rawTextBuilder) {
public void sendMessageTranslation(String translate, List<String> parameters) {
this.getNetworkSession().onMessageTranslation(translate, parameters);
}

@Override
public void clean() {
this.getServer().removeOnlinePlayer(this);
super.clean();
}
}

0 comments on commit 64fa62e

Please sign in to comment.