Skip to content

Commit 5f1f8e1

Browse files
Rewrite nextFreeId to not use a goto
1 parent fc0b71b commit 5f1f8e1

2 files changed

Lines changed: 26 additions & 15 deletions

File tree

fCraft/Commands/CpeCommands.cs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,13 @@ private static void EntityHandler(Player player, CommandReader cmd) {
159159
string skinString1 = (cmd.Next() ?? entityName);
160160
if (skinString1 != null) skinString1 = ParseSkin(skinString1);
161161

162-
entity = Entity.Create(entityName, skinString1, requestedModel, player.World, player.Position, getNewID(player.World));
163-
player.Message("Successfully created entity {0}&S with id:{1} and skin {2}.", entity.Name, entity.ID, entity.Skin, entity.Name);
162+
sbyte newEntityId = Entity.NextFreeID(player.World.Name);
163+
if (newEntityId == Packet.SelfId) {
164+
player.Message("No more free ids left! Remove an entity first.");
165+
} else {
166+
entity = Entity.Create(entityName, skinString1, requestedModel, player.World, player.Position, newEntityId);
167+
player.Message("Successfully created entity {0}&S with id:{1} and skin {2}.", entity.Name, entity.ID, entity.Skin, entity.Name);
168+
}
164169
break;
165170
case "remove":
166171
player.Message("{0} was removed from {1}", entity.Name, player.World.Name);
@@ -273,18 +278,6 @@ private static void EntityHandler(Player player, CommandReader cmd) {
273278
}
274279
}
275280

276-
public static sbyte getNewID(World world) {
277-
sbyte i = 1;
278-
go:
279-
foreach (Entity entity in Entity.AllIn(world)) {
280-
if (entity.ID == i) {
281-
i++;
282-
goto go;
283-
}
284-
}
285-
return i;
286-
}
287-
288281
#endregion
289282

290283
#region ChangeModel

fCraft/World/Entity.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,23 @@ public static void ReloadAll() {
155155
EntityList.Clear();
156156
LoadAll();
157157
SpawnAll();
158+
}
159+
160+
public unsafe static sbyte NextFreeID(string world) {
161+
byte* used = stackalloc byte[128];
162+
for (int i = 0; i < 128; i++)
163+
used[i] = 0;
164+
165+
foreach (Entity entity in Entity.AllIn(world)) {
166+
if (entity.ID >= 0) used[entity.ID] = 1;
167+
}
168+
169+
for (int i = 0; i <= sbyte.MaxValue; i++ ) {
170+
if (used[i] == 0) return (sbyte)i;
171+
}
172+
return Packet.SelfId;
158173
}
174+
159175

160176
public static void SaveAll(bool verbose) {
161177
try {
@@ -216,7 +232,9 @@ public static void OldLoad() {
216232
if (entity.World == null) continue;
217233

218234
sbyte id;
219-
if (!sbyte.TryParse(entityData[3], out id)) { id = CpeCommands.getNewID(world); }
235+
if (!sbyte.TryParse(entityData[3], out id)) id = NextFreeID(entity.World);
236+
if (id == Packet.SelfId) continue;
237+
220238
entity.ID = id;
221239
entity.Name = entityData[0] ?? entity.ID.ToString();
222240
entity.Skin = entityData[1] ?? entity.Name;

0 commit comments

Comments
 (0)