public override void OnReceivedClientPacket(IServerPlayer player, int packetid, byte[] data) { if (packetid < 1000) { Inventory.InvNetworkUtil.HandleClientPacket(player, packetid, data); return; } if (packetid == 1000) { EnumTransactionResult result = Inventory.TryBuySell(player); if (result == EnumTransactionResult.Success) { (Api as ICoreServerAPI).WorldManager.GetChunk(ServerPos.AsBlockPos)?.MarkModified(); AnimManager.StopAnimation("idle"); AnimManager.StartAnimation(new AnimationMetaData() { Animation = "nod", Code = "nod", Weight = 10, EaseOutSpeed = 10000, EaseInSpeed = 10000 }); TreeAttribute tree = new TreeAttribute(); Inventory.ToTreeAttributes(tree); (Api as ICoreServerAPI).Network.BroadcastEntityPacket(EntityId, 1234, tree.ToBytes()); } } }
private void OnNwTestCmd(IServerPlayer player, int groupId, CmdArgs args) { serverChannel.BroadcastPacket(new NetworkApiTestMessage() { message = "Hello World!", }); }
private void Event_DidBreakBlock(IServerPlayer byPlayer, int oldblockId, BlockSelection blockSel) { if (tmpPos != null && blockSel.Position.Equals(tmpPos)) { taskState = 4; } }
private void PlayerJoin(IServerPlayer byPlayer) { sChannel.SendPacket(new SwapMessage() { SwapPairs = JsonConvert.SerializeObject(SwapPairs) }, byPlayer); }
private void Event_PlayerJoin(IServerPlayer byPlayer) { sapi.Network.GetChannel("riftWeather").SendPacket(new SpawnPatternPacket() { Pattern = curPattern }, byPlayer); }
public static void RandomTeleport(IServerPlayer player, int range = -1) { try { ICoreServerAPI api = player.Entity.Api as ICoreServerAPI; int x, y, z; if (range != -1) { x = api.World.Rand.Next(range * 2) - range + player.Entity.Pos.XYZInt.X; z = api.World.Rand.Next(range * 2) - range + player.Entity.Pos.XYZInt.Z; } else { x = api.World.Rand.Next(api.WorldManager.MapSizeX); z = api.World.Rand.Next(api.WorldManager.MapSizeZ); } //y = (api.WorldManager.GetSurfacePosY(x, z) ?? api.WorldManager.MapSizeY); //y += 2; y = api.WorldManager.MapSizeY; player.SendMessageAsClient("/tp =" + x + " " + y + " =" + z); player.Entity.PositionBeforeFalling = new Vec3d(x, 0, z); } catch (Exception e) { player?.Entity?.Api?.Logger?.ModError("Failed to teleport player to random location."); player?.Entity?.Api?.Logger?.ModError(e.Message); } }
private void Event_PlayerJoin(IServerPlayer byPlayer) { serverChannel?.SendPacket(new PrivGrantsData() { privGrantsByOwningPlayerUid = privGrantsByOwningPlayerUid }, byPlayer); }
private void CmdGenHouse(IServerPlayer player, int groupId, CmdArgs args) { IBlockAccessor blockAccessor = api.World.GetBlockAccessorBulkUpdate(true, true); int blockID = api.WorldManager.GetBlockId(new AssetLocation("log-placed-oak-ud")); BlockPos pos = player.Entity.Pos.AsBlockPos; for (int dx = -3; dx <= 3; dx++) { for (int dz = -3; dz <= 3; dz++) { for (int dy = 0; dy <= 3; dy++) { if (Math.Abs(dx) != 3 && Math.Abs(dz) != 3 && dy < 3) { continue; // Hollow } if (dx == -3 && dz == 0 && dy < 2) { continue; // Door } blockAccessor.SetBlock(blockID, pos.AddCopy(dx, dy, dz)); } } } blockAccessor.Commit(); }
private void onCmdRiftTest(IServerPlayer player, int groupId, CmdArgs args) { Vec3d pos = player.Entity.Pos.XYZ; string cmd = args.PopWord(); if (cmd == null) { player.SendMessage(groupId, rifts.Count + " rifts loaded", EnumChatType.Notification); return; } if (cmd == "clear") { rifts.Clear(); } if (cmd == "fade") { foreach (var rift in rifts) { rift.DieAtTotalHours = Math.Min(rift.DieAtTotalHours, api.World.Calendar.TotalHours + 0.2); } } if (cmd == "spawn") { for (int i = 0; i < 200; i++) { double distance = spawnMinDistance + api.World.Rand.NextDouble() * spawnAddDistance; double angle = api.World.Rand.NextDouble() * GameMath.TWOPI; double dz = distance * Math.Sin(angle); double dx = distance * Math.Cos(angle); Vec3d riftPos = pos.AddCopy(dx, 0, dz); BlockPos bpos = new BlockPos((int)riftPos.X, 0, (int)riftPos.Z); bpos.Y = api.World.BlockAccessor.GetTerrainMapheightAt(bpos); var block = api.World.BlockAccessor.GetBlock(bpos); if (block.IsLiquid() && api.World.Rand.NextDouble() > 0.1) { continue; } float size = 2 + (float)api.World.Rand.NextDouble() * 4f; riftPos.Y = bpos.Y + size / 2f + 1; rifts.Add(new Rift() { Position = riftPos, Size = size, SpawnedTotalHours = api.World.Calendar.TotalHours, DieAtTotalHours = api.World.Calendar.TotalHours + 8 + api.World.Rand.NextDouble() * 48 }); } } BroadCastRifts(); }
private void OnCmdNpcs(IServerPlayer player, int groupId, CmdArgs args) { string cmd = args.PopWord(); bool exec = cmd == "startall" || cmd == "startallrandom"; if (cmd != "startall" && cmd == "stopall" || cmd == "startallrandom") { player.SendMessage(groupId, "Unknown command", EnumChatType.Notification); } foreach (var val in sapi.World.LoadedEntities) { EntityAnimalBot npc = val.Value as EntityAnimalBot; if (npc != null) { if (exec) { if (cmd == "startallrandom") { sapi.Event.RegisterCallback((dt) => npc.StartExecuteCommands(), (int)(sapi.World.Rand.NextDouble() * 200)); } else { npc.StartExecuteCommands(); } } else { npc.StopExecuteCommands(); } } } }
private void CmdBlock(IServerPlayer player, int groupId, CmdArgs args) { int blockID = api.WorldManager.GetBlockId(new AssetLocation("log-placed-birch-ud")); BlockPos pos = player.Entity.Pos.HorizontalAheadCopy(2).AsBlockPos; api.World.BlockAccessor.SetBlock(blockID, pos); }
public CGameSession(FreelancerGame g, IPacketConnection connection) { Game = g; this.connection = connection; rpcServer = new RemoteServerPlayer(connection, this); ResponseHandler = new NetResponseHandler(); }
private BlockPos DetermineGraveSpot(IServerPlayer player) { var radius = GraveModConfig.Current.GraveRadius; var gravePos = player?.Entity?.PositionBeforeFalling?.AsBlockPos ?? player?.Entity?.Pos?.AsBlockPos; if (gravePos != null) { //first check the current position if (_serverApi.World.BlockAccessor.GetBlock(gravePos)?.IsReplacableBy(_graveBlock) == true) { return(gravePos); } //search surrounding blocks for a useful location _serverApi.World.BlockAccessor.SearchBlocks( gravePos.AddCopy(-radius, -radius, -radius), gravePos.AddCopy(radius, radius, radius), (block, blockPos) => { if (block != null && block.IsReplacableBy(_graveBlock)) { gravePos = blockPos; return(false); } return(true); }); } return(gravePos); //this is either a valid position in the radius or the last position }
private void Event_DidPlaceBlock(IServerPlayer byPlayer, int oldblockId, BlockSelection blockSel, ItemStack withItemStack) { IMapChunk mapchunk = api.World.BlockAccessor.GetMapChunkAtBlockPos(blockSel.Position); if (mapchunk == null) { return; } int lx = blockSel.Position.X % chunksize; int lz = blockSel.Position.Z % chunksize; int y = mapchunk.RainHeightMap[lz * chunksize + lx]; int ly = y % chunksize; IWorldChunk chunk = api.World.BlockAccessor.GetChunkAtBlockPos(blockSel.Position.X, y, blockSel.Position.Z); if (chunk == null) { return; } chunk.Unpack(); int blockId = chunk.Blocks[(ly * chunksize + lz) * chunksize + lx]; if (blockId == 0) { int cx = blockSel.Position.X / chunksize; int cz = blockSel.Position.Z / chunksize; api.World.Logger.Notification("Huh. Found air block in rain map at chunk pos {0}/{1}. That seems invalid, will regenerate rain map", cx, cz); rebuildRainmap(cx, cz); } }
private void SubcmdSkinSelectable(IServerPlayer player, string playername, int groupId, CmdArgs args) { /*if (!player.HasPrivilege(Privilege.grantrevoke)) * { * Error(player, groupId, Lang.Get("Insufficient Privileges")); * return; * } * * * bool? on = args.PopBool(); * * if (on == null) * { * Success(player, groupId, "Did select flag = " + player.WorldData.DidSelectSkin); * return; * } * * if (on == true) * { * player.WorldData.DidSelectSkin = false; * Success(player, groupId, "Player can now select skin on reload again."); * } * else * { * player.WorldData.DidSelectSkin = true; * Success(player, groupId, "Player can no longer select skin."); * }*/ }
private void OnCmdErrRep(IServerPlayer player, int groupId, CmdArgs args) { bool on = (bool)args.PopBool(true); player.ServerData.CustomPlayerData["errorReporting"] = on ? "1" : "0"; player.SendMessage(groupId, Lang.Get("Error reporting now {0}", on ? "on" : "off"), EnumChatType.Notification); }
public override void OnHeldAttackStart(IItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel, ref EnumHandHandling handling) { if (byEntity.World.Side == EnumAppSide.Client) { handling = EnumHandHandling.PreventDefaultAction; return; } if (blockSel == null) { return; } ModSystemBlockReinforcement bre = byEntity.Api.ModLoader.GetModSystem <ModSystemBlockReinforcement>(); IServerPlayer player = (byEntity as EntityPlayer).Player as IServerPlayer; if (player == null) { return; } string errorCode = ""; if (!bre.TryRemoveReinforcement(blockSel.Position, player, ref errorCode)) { player.SendMessage(GlobalConstants.CurrentChatGroup, "Cannot remove reinforcement: " + errorCode, EnumChatType.Notification); return; } BlockPos pos = blockSel.Position; byEntity.World.PlaySoundAt(new AssetLocation("blockreinforcement", "sounds/reinforce"), pos.X, pos.Y, pos.Z, null); handling = EnumHandHandling.PreventDefaultAction; }
public bool AreAllPlayersSleeping() { int quantitySleeping = 0; int quantityAwake = 0; foreach (IPlayer player in sapi.World.AllOnlinePlayers) { IServerPlayer splr = player as IServerPlayer; if (splr.ConnectionState != EnumClientState.Playing || splr.WorldData.CurrentGameMode == EnumGameMode.Spectator) { continue; } IMountable mount = player.Entity?.MountedOn; if (mount != null && mount is BlockEntityBed) { quantitySleeping++; } else { quantityAwake++; } } return(quantitySleeping > 0 && quantityAwake == 0); }
public void reset(EntityPlayer entity, bool message) { foreach (var stats in entity.Stats) { entity.Stats.Remove(stats.Key, "potionmod"); } EntityBehaviorHealth ebh = entity.GetBehavior <EntityBehaviorHealth>(); ebh.MarkDirty(); if (entity.WatchedAttributes.HasAttribute("glow")) { entity.WatchedAttributes.RemoveAttribute("glow"); } if (entity.WatchedAttributes.HasAttribute("potionid")) { long effectIdGametick = entity.WatchedAttributes.GetLong("potionid"); entity.World.UnregisterGameTickListener(effectIdGametick); effectDuration = 0; effectHealth = 0; effectTickSec = 0; entity.WatchedAttributes.RemoveAttribute("potionid"); } if (message) { IServerPlayer player = (entity.World.PlayerByUid((entity as EntityPlayer).PlayerUID) as IServerPlayer); player.SendMessage(GlobalConstants.InfoLogChatGroup, "You feel the effects of the potion disapate", EnumChatType.Notification); } }
private void OnChangePlayerModeMessage(IPlayer fromPlayer, ChangePlayerModePacket plrmode) { IServerPlayer plr = fromPlayer as IServerPlayer; bool freeMoveAllowed = plr.HasPrivilege(Privilege.freemove); bool gameModeAllowed = plr.HasPrivilege(Privilege.gamemode); bool pickRangeAllowed = plr.HasPrivilege(Privilege.pickingrange); if (plrmode.axisLock != null) { fromPlayer.WorldData.FreeMovePlaneLock = (EnumFreeMovAxisLock)plrmode.axisLock; } if (plrmode.pickingRange != null && pickRangeAllowed) { fromPlayer.WorldData.PickingRange = (float)plrmode.pickingRange; } if (plrmode.fly != null) { fromPlayer.WorldData.FreeMove = (bool)plrmode.fly && freeMoveAllowed; } if (plrmode.noclip != null) { fromPlayer.WorldData.NoClip = (bool)plrmode.noclip && freeMoveAllowed; } }
public void SetPlayerPrivilege(IServerPlayer owningPlayer, int chatGroupId, string forPlayerUid, EnumBlockAccessFlags access) { ReinforcedPrivilegeGrants grants; if (!privGrantsByOwningPlayerUid.TryGetValue(owningPlayer.PlayerUID, out grants)) { grants = new ReinforcedPrivilegeGrants(); privGrantsByOwningPlayerUid[owningPlayer.PlayerUID] = grants; } if (access == EnumBlockAccessFlags.None) { if (grants.PlayerGrants.Remove(forPlayerUid)) { owningPlayer.SendMessage(chatGroupId, Lang.Get("Ok, privilege revoked from player."), EnumChatType.CommandSuccess); } else { owningPlayer.SendMessage(chatGroupId, Lang.Get("No action taken. Player does not have any privilege to your reinforced blocks."), EnumChatType.CommandSuccess); } } else { grants.PlayerGrants[forPlayerUid] = access; owningPlayer.SendMessage(chatGroupId, Lang.Get("Ok, Privilege for player set."), EnumChatType.CommandSuccess); } SyncPrivData(); }
private void ExportArea(string filename, BlockPos start, BlockPos end, IServerPlayer sendToPlayer = null) { BlockSchematic blockdata = CopyArea(start, end); int exported = blockdata.BlockIds.Count; string outfilepath = Path.Combine(exportFolderPath, filename); if (sendToPlayer != null) { serverChannel.SendPacket <SchematicJsonPacket>(new SchematicJsonPacket() { Filename = filename, JsonCode = blockdata.ToJson() }, sendToPlayer); Good(exported + " blocks schematic sent to client."); } else { string error = blockdata.Save(outfilepath); if (error != null) { Good("Failed exporting: " + error); } else { Good(exported + " blocks exported."); } } }
private void onSetTlPos(IServerPlayer player, int groupId, CmdArgs args) { BlockPos pos = player.CurrentBlockSelection.Position; BlockEntityStaticTranslocator bet = sapi.World.BlockAccessor.GetBlockEntity(pos) as BlockEntityStaticTranslocator; if (bet == null) { player.SendMessage(groupId, "Not looking at a translocator. Must look at one to set its target", EnumChatType.CommandError); return; } Vec3d spawnpos = sapi.World.DefaultSpawnPosition.XYZ; spawnpos.Y = 0; Vec3d targetpos = args.PopFlexiblePos(player.Entity.Pos.XYZ, spawnpos); if (targetpos == null) { player.SendMessage(groupId, "Invalid position supplied. Syntax: [coord] [coord] [coord] or =[abscoord] =[abscoord] =[abscoord]", EnumChatType.CommandError); return; } bet.tpLocation = targetpos.AsBlockPos; bet.MarkDirty(true); player.SendMessage(groupId, "Target position set.", EnumChatType.CommandError); }
private void OnPlayerJoin(IPlayer player) { fromPlayer = player as IServerPlayer; WorldEditWorkspace workspace = GetOrCreateWorkSpace(player); IBlockAccessorRevertable revertableBlockAccess = sapi.World.GetBlockAccessorRevertable(true, true); // Initialize all tools once to build up the workspace for the client gui tool options foreach (var val in ToolRegistry.ToolTypes) { ToolRegistry.InstanceFromType(val.Key, workspace, revertableBlockAccess); } if (workspace.ToolsEnabled) { if (workspace.ToolInstance != null) { EnumHighlightBlocksMode mode = EnumHighlightBlocksMode.CenteredToSelectedBlock; if (workspace.ToolOffsetMode == EnumToolOffsetMode.Attach) { mode = EnumHighlightBlocksMode.AttachedToSelectedBlock; } sapi.World.HighlightBlocks(player, (int)EnumHighlightSlot.Brush, workspace.ToolInstance.GetBlockHighlights(this), workspace.ToolInstance.GetBlockHighlightColors(this), mode); } } else { workspace.HighlightSelectedArea(); } }
private void OnServerReceiveTeleportMsg(IServerPlayer fromPlayer, TeleportMsg msg) { if (!msg.DoRemove) { if (Teleports.ContainsKey(msg.Pos)) { Teleports[msg.Pos] = msg.Data; } else { Teleports.Add(msg.Pos, msg.Data); } } else { if (Teleports.ContainsKey(msg.Pos)) { Teleports.Remove(msg.Pos); } } if (!msg.Synced) { serverChannel.BroadcastPacket(new TeleportMsg( msg.Pos, msg.Data, msg.DoRemove, true )); } }
private void OnSelectedMetalMessage(IServerPlayer player, SelectedMetalMessage message) { EntityBehaviorAllomancy allomancy = (EntityBehaviorAllomancy)(player.Entity.GetBehavior("allomancy")); if (message._metal_id < -1 || message._metal_id >= MistModSystem.METALS.Length) { return; } if (message._metal_id == -1) // The client doesn't know what the selected metal is { string selectedMetal = allomancy.Helper.GetSelectedMetal(); int result = -1; if (selectedMetal != "none") { result = Array.IndexOf(MistModSystem.METALS, selectedMetal); } Channel.SendPacket(new SelectedMetalMessage(result), player); } else // The client does know what the selected metal is. { string selectedMetal = MistModSystem.METALS[message._metal_id]; allomancy.Helper.SetSelectedMetal(selectedMetal); } allomancy.Helper.Debug(); }
protected void OnClientRequestPacket(IServerPlayer player, MechClientRequestPacket networkMessage) { if (data.networksById.TryGetValue(networkMessage.networkId, out MechanicalNetwork nw)) { nw.SendBlocksUpdateToClient(player); } }
void TreeLineup(IServerPlayer player, CmdArgs arguments) { if (arguments.Length < 2) { player.SendMessage(groupId, "/wgen treelineup {treeWorldPropertyCode} [0.1 - 3]", EnumChatType.CommandError); return; } EntityPos pos = player.Entity.Pos; BlockPos center = pos.HorizontalAheadCopy(25).AsBlockPos; IBlockAccessor blockAccessor = api.WorldManager.GetBlockAccessorBulkUpdate(true, true, true); int size = 12; for (int dx = -2 * size; dx < 2 * size; dx++) { for (int dz = -size; dz < size; dz++) { for (int dy = 0; dy < 2 * size; dy++) { blockAccessor.SetBlock(0, center.AddCopy(dx, dy, dz)); } } } treeGenerators.ReloadTreeGenerators(); treeGenerators.RunGenerator(new AssetLocation(arguments[1]), blockAccessor, center.AddCopy(0, -1, 0)); treeGenerators.RunGenerator(new AssetLocation(arguments[1]), blockAccessor, center.AddCopy(-9, -1, 0)); treeGenerators.RunGenerator(new AssetLocation(arguments[1]), blockAccessor, center.AddCopy(9, -1, 0)); blockAccessor.Commit(); }
public void FindMatches(IServerPlayer player, bool DL = false) { MostLikely.Clear(); RePopulate(); Search(player, MissingBlocks, NotMissingBlocks, "Block", DL); Search(player, MissingItems, NotMissingItems, "Item", DL); }
public void GiveKit(IServerPlayer player, string kitName) { var kit = GetLoadedKits().kits.Find( x => x.name == kitName ); if (kit != null) { if (!player.HasPrivilege(Privilege.ignoreCooldowns)) { var cooldown = GetCooldownManager().GetCooldown(player.PlayerUID, kitName); if (cooldown > 0) { player.SendErr($"You must wait {cooldown} sec. to use this kit"); return; } } if (!player.HasPrivilege($"{Privilege.kit}.{kit.name}")) { player.SendErr($"You don't have access to kit {kit.name}"); return; } player.SendOk($"Giving kit {kit.name}"); // TODO: if inventory full, should use player.Entity.World.SpawnItemEntity(); kit.items.ForEach( item => player.GiveItemStack(item.type, item.code, item.amount) ); GetCooldownManager().SetCooldown(player.PlayerUID, kitName, kit.delay); } else { player.SendErr($"{kitName} not found"); } }