internal void FillFill(Game game, Vector3IntRef a_, Vector3IntRef b_) { int startx = MathCi.MinInt(a_.X, b_.X); int endx = MathCi.MaxInt(a_.X, b_.X); int starty = MathCi.MinInt(a_.Y, b_.Y); int endy = MathCi.MaxInt(a_.Y, b_.Y); int startz = MathCi.MinInt(a_.Z, b_.Z); int endz = MathCi.MaxInt(a_.Z, b_.Z); for (int x = startx; x <= endx; x++) { for (int y = starty; y <= endy; y++) { for (int z = startz; z <= endz; z++) { if (fillarea.Count() > game.fillAreaLimit) { ClearFillArea(game); return; } if (!game.IsFillBlock(game.map.GetBlock(x, y, z))) { fillarea.Set(x, y, z, game.map.GetBlock(x, y, z)); game.SetBlock(x, y, z, game.d_Data.BlockIdFillArea()); game.RedrawBlock(x, y, z); } } } } }
public override void OnNewFrameFixed(Game game_, int entity, float dt) { game = game_; if (game.guistate == GuiState.MapLoading) { return; } movespeednow = game.MoveSpeedNow(); game.controls.movedx = MathCi.ClampFloat(game.controls.movedx, -1, 1); game.controls.movedy = MathCi.ClampFloat(game.controls.movedy, -1, 1); Controls move = game.controls; jumpstartacceleration = 13.333f * constGravity; // default jumpstartaccelerationhalf = 9 * constGravity; acceleration.SetDefault(); game.soundnow = new BoolRef(); if (game.FollowId() != null && game.FollowId().value == game.LocalPlayerId) { move.movedx = 0; move.movedy = 0; move.moveup = false; move.wantsjump = false; } Update(game.player.position, move, dt, game.soundnow, Vector3Ref.Create(game.pushX, game.pushY, game.pushZ), game.entities[game.LocalPlayerId].drawModel.ModelHeight); }
void ApplyLightEmitting(int[] workportionArr, byte[] worklightArr, int[] dataLightRadius) { int[] radiusArr = dataLightRadius; const int portionsize = 16; const int portionsize3 = portionsize * portionsize * portionsize; Vector3IntRef p = new Vector3IntRef(); for (int pos = 0; pos < portionsize3; pos++) { if (workportionArr[pos] >= 10) //optimization { if (radiusArr[workportionArr[pos]] != 0) //optimization { if (radiusArr[workportionArr[pos]] > worklightArr[pos]) { MapUtilCi.PosInt(pos, portionsize, portionsize, p); int xx = p.X; int yy = p.Y; int zz = p.Z; int l = radiusArr[workportionArr[pos]]; lighttoflood.Push(xx); lighttoflood.Push(yy); lighttoflood.Push(zz); worklightArr[pos] = Game.IntToByte(MathCi.MaxInt(l, worklightArr[pos])); } } } } }
internal void LimitThirdPersonCameraToWalls(Game game, Vector3Ref eye, Vector3Ref target, FloatRef curtppcameradistance) { float one = 1; Vector3Ref ray_start_point = target; Vector3Ref raytarget = eye; Line3D pick = new Line3D(); float raydirX = (raytarget.X - ray_start_point.X); float raydirY = (raytarget.Y - ray_start_point.Y); float raydirZ = (raytarget.Z - ray_start_point.Z); float raydirLength1 = game.Length(raydirX, raydirY, raydirZ); raydirX /= raydirLength1; raydirY /= raydirLength1; raydirZ /= raydirLength1; raydirX = raydirX * (game.tppcameradistance + 1); raydirY = raydirY * (game.tppcameradistance + 1); raydirZ = raydirZ * (game.tppcameradistance + 1); pick.Start = Vec3.FromValues(ray_start_point.X, ray_start_point.Y, ray_start_point.Z); pick.End = new float[3]; pick.End[0] = ray_start_point.X + raydirX; pick.End[1] = ray_start_point.Y + raydirY; pick.End[2] = ray_start_point.Z + raydirZ; //pick terrain IntRef pick2Count = new IntRef(); BlockPosSide[] pick2 = game.Pick(game.s, pick, pick2Count); if (pick2Count.value > 0) { BlockPosSide pick2nearest = game.Nearest(pick2, pick2Count.value, ray_start_point.X, ray_start_point.Y, ray_start_point.Z); //pick2.Sort((a, b) => { return (FloatArrayToVector3(a.blockPos) - ray_start_point).Length.CompareTo((FloatArrayToVector3(b.blockPos) - ray_start_point).Length); }); float pickX = pick2nearest.blockPos[0] - target.X; float pickY = pick2nearest.blockPos[1] - target.Y; float pickZ = pick2nearest.blockPos[2] - target.Z; float pickdistance = game.Length(pickX, pickY, pickZ); curtppcameradistance.value = MathCi.MinFloat(pickdistance - 1, curtppcameradistance.value); if (curtppcameradistance.value < one * 3 / 10) { curtppcameradistance.value = one * 3 / 10; } } float cameraDirectionX = target.X - eye.X; float cameraDirectionY = target.Y - eye.Y; float cameraDirectionZ = target.Z - eye.Z; float raydirLength = game.Length(raydirX, raydirY, raydirZ); raydirX /= raydirLength; raydirY /= raydirLength; raydirZ /= raydirLength; eye.X = target.X + raydirX * curtppcameradistance.value; eye.Y = target.Y + raydirY * curtppcameradistance.value; eye.Z = target.Z + raydirZ * curtppcameradistance.value; }
public override InterpolatedObject InterpolatedState(int timeMilliseconds) { int curtimeMilliseconds = timeMilliseconds; int interpolationtimeMilliseconds = curtimeMilliseconds - DELAYMILLISECONDS; int p1; int p2; if (receivedCount == 0) { return(null); } InterpolatedObject result; if (receivedCount > 0 && interpolationtimeMilliseconds < received[0].timestampMilliseconds) { p1 = 0; p2 = 0; } //extrapolate else if (EXTRAPOLATE && (receivedCount >= 2) && interpolationtimeMilliseconds > received[receivedCount - 1].timestampMilliseconds) { p1 = receivedCount - 2; p2 = receivedCount - 1; interpolationtimeMilliseconds = MathCi.MinInt(interpolationtimeMilliseconds, received[receivedCount - 1].timestampMilliseconds + EXTRAPOLATION_TIMEMILLISECONDS); } else { p1 = 0; for (int i = 0; i < receivedCount; i++) { if (received[i].timestampMilliseconds <= interpolationtimeMilliseconds) { p1 = i; } } p2 = p1; if (receivedCount - 1 > p1) { p2++; } } if (p1 == p2) { result = received[p1].content; } else { float one = 1; result = req.Interpolate(received[p1].content, received[p2].content, (one * (interpolationtimeMilliseconds - received[p1].timestampMilliseconds) / (received[p2].timestampMilliseconds - received[p1].timestampMilliseconds))); } return(result); }
public override void OnNewFrameFixed(Game game, NewFrameEventArgs args) { if (game.reloadstartMilliseconds != 0 && (game.one * (game.platform.TimeMillisecondsFromStart() - game.reloadstartMilliseconds) / 1000) > game.DeserializeFloat(game.blocktypes[game.reloadblock].ReloadDelayFloat)) { { int loaded = game.TotalAmmo[game.reloadblock]; loaded = MathCi.MinInt(game.blocktypes[game.reloadblock].AmmoMagazine, loaded); game.LoadedAmmo[game.reloadblock] = loaded; game.reloadstartMilliseconds = 0; game.reloadblock = -1; } } }
public void AddPoint(float x, float y, float z) { //if is empty if (MinEdge == null || MaxEdge == null || (MinEdge[0] == 0 && MinEdge[1] == 0 && MinEdge[2] == 0 && MaxEdge[0] == 0 && MaxEdge[1] == 0 && MaxEdge[2] == 0)) { MinEdge = Vec3.FromValues(x, y, z); MaxEdge = Vec3.FromValues(x, y, z); } MinEdge[0] = MathCi.MinFloat(MinEdge[0], x); MinEdge[1] = MathCi.MinFloat(MinEdge[1], y); MinEdge[2] = MathCi.MinFloat(MinEdge[2], z); MaxEdge[0] = MathCi.MaxFloat(MaxEdge[0], x); MaxEdge[1] = MathCi.MaxFloat(MaxEdge[1], y); MaxEdge[2] = MathCi.MaxFloat(MaxEdge[2], z); }
void UpdateTitleFps(float dt) { GamePlatform p = m.GetPlatform(); fpscount++; longestframedt = MathCi.MaxFloat(longestframedt, dt); float elapsed = one * (p.TimeMillisecondsFromStart() - lasttitleupdateMilliseconds) / 1000; if (elapsed >= 1) { string fpstext1 = ""; lasttitleupdateMilliseconds = p.TimeMillisecondsFromStart(); fpstext1 = StringTools.StringAppend(p, fpstext1, p.StringFormat("FPS: {0}", p.IntToString(p.FloatToInt((one * fpscount) / elapsed)))); fpstext1 = StringTools.StringAppend(p, fpstext1, p.StringFormat(" (min: {0})", p.IntToString(p.FloatToInt(one / longestframedt)))); longestframedt = 0; fpscount = 0; m.GetPerformanceInfo().Set("fps", fpstext1); string s = ""; string[] l = new string[64]; int lCount = 0; for (int i = 0; i < m.GetPerformanceInfo().count; i++) { if (m.GetPerformanceInfo().items[i] == null) { continue; } l[lCount++] = m.GetPerformanceInfo().items[i].value; } int perline = 2; for (int i = 0; i < lCount; i++) { s = StringTools.StringAppend(p, s, l[i]); if ((i % perline == 0) && (i != lCount - 1)) { s = StringTools.StringAppend(p, s, ", "); } if (i % perline != 0) { s = StringTools.StringAppend(p, s, "\n"); } } fpstext = s; } }
void UpdateStatisticsText(float dt) { GamePlatform p = m.GetPlatform(); fpscount++; longestframedt = MathCi.MaxFloat(longestframedt, dt); float elapsed = one * (p.TimeMillisecondsFromStart() - lasttitleupdateMilliseconds) / 1000; if (elapsed >= 1) { lasttitleupdateMilliseconds = p.TimeMillisecondsFromStart(); string fpstext1 = p.IntToString(p.FloatToInt((one * fpscount) / elapsed)); fpstext1 = StringTools.StringAppend(p, fpstext1, p.StringFormat(" (min: {0})", p.IntToString(p.FloatToInt(one / longestframedt)))); longestframedt = 0; fpscount = 0; m.GetPerformanceInfo().Set("FPS", fpstext1); StatsLineCount = 0; for (int i = 0; i < m.GetPerformanceInfo().size; i++) { if (m.GetPerformanceInfo().items[i] == null) { continue; } if (m.GetPerformanceInfo().items[i].key == "Chunk updates") { UpdateChunkHistory(p.IntParse(m.GetPerformanceInfo().items[i].value)); } if (m.GetPerformanceInfo().items[i].key == "Ping") { UpdatePingHistory(p.IntParse(m.GetPerformanceInfo().items[i].value)); } if (StatsLineCount >= StatsMaxLineCount) { // Prevent running out of bounds break; } StatsLines[StatsLineCount++] = p.StringFormat2("{0}: {1}", m.GetPerformanceInfo().items[i].key, m.GetPerformanceInfo().items[i].value); } } }
//tiles = 16 means 16 x 16 atlas public BitmapCi[] Atlas2dInto1d(GamePlatform p, BitmapCi atlas2d_, int tiles, int atlassizezlimit, IntRef retCount) { BitmapData_ orig = BitmapData_.CreateFromBitmap(p, atlas2d_); int tilesize = orig.width / tiles; int atlasescount = MathCi.MaxInt(1, (tiles * tiles * tilesize) / atlassizezlimit); BitmapCi[] atlases = new BitmapCi[128]; int atlasesCount = 0; BitmapData_ atlas1d = null; for (int i = 0; i < tiles * tiles; i++) { int x = i % tiles; int y = i / tiles; int tilesinatlas = (tiles * tiles / atlasescount); if (i % tilesinatlas == 0) { if (atlas1d != null) { atlases[atlasesCount++] = atlas1d.ToBitmap(p); } atlas1d = BitmapData_.Create(tilesize, atlassizezlimit); } for (int xx = 0; xx < tilesize; xx++) { for (int yy = 0; yy < tilesize; yy++) { int c = orig.GetPixel(x * tilesize + xx, y * tilesize + yy); atlas1d.SetPixel(xx, (i % tilesinatlas) * tilesize + yy, c); } } } atlases[atlasesCount++] = atlas1d.ToBitmap(p); retCount.value = atlasescount; return(atlases); }
void LightEmitting(int[] workportion, byte[] worklight, int[] dataLightRadius, bool[] dataTransparent) { const int portionsize = 16; const int portionsize3 = portionsize * portionsize * portionsize; for (int pos = 0; pos < portionsize3; pos++) { if (workportion[pos] >= 10) //optimization { if (dataLightRadius[workportion[pos]] != 0) //optimization { if (dataLightRadius[workportion[pos]] > worklight[pos]) { int xx = MapUtilCi.PosX(pos, portionsize, portionsize); int yy = MapUtilCi.PosY(pos, portionsize, portionsize); int zz = MapUtilCi.PosZ(pos, portionsize, portionsize); int l = dataLightRadius[workportion[pos]]; worklight[pos] = Game.IntToByte(MathCi.MaxInt(l, worklight[pos])); flood.FloodLight(workportion, worklight, xx, yy, zz, dataLightRadius, dataTransparent); } } } } }
public override void OnKeyDown(Game game_, KeyEventArgs args) { if (game.guistate != GuiState.Normal) { //Don't open chat when not in normal game return; } int eKey = args.GetKeyCode(); if (eKey == game.GetKey(GlKeys.Number7) && game.IsShiftPressed && game.GuiTyping == TypingState.None) // don't need to hit enter for typing commands starting with slash { game.GuiTyping = TypingState.Typing; game.IsTyping = true; game.GuiTypingBuffer = ""; game.IsTeamchat = false; args.SetHandled(true); return; } if (eKey == game.GetKey(GlKeys.PageUp) && game.GuiTyping == TypingState.Typing) { ChatPageScroll++; args.SetHandled(true); } if (eKey == game.GetKey(GlKeys.PageDown) && game.GuiTyping == TypingState.Typing) { ChatPageScroll--; args.SetHandled(true); } ChatPageScroll = MathCi.ClampInt(ChatPageScroll, 0, game.ChatLinesCount / ChatLinesMaxToDraw); if (eKey == game.GetKey(GlKeys.Enter) || eKey == game.GetKey(GlKeys.KeypadEnter)) { if (game.GuiTyping == TypingState.Typing) { game.typinglog[game.typinglogCount++] = game.GuiTypingBuffer; game.typinglogpos = game.typinglogCount; game.ClientCommand(game.GuiTypingBuffer); game.GuiTypingBuffer = ""; game.IsTyping = false; game.GuiTyping = TypingState.None; game.platform.ShowKeyboard(false); } else if (game.GuiTyping == TypingState.None) { game.StartTyping(); } else if (game.GuiTyping == TypingState.Ready) { game.platform.ConsoleWriteLine("Keyboard_KeyDown ready"); } args.SetHandled(true); return; } if (game.GuiTyping == TypingState.Typing) { int key = eKey; if (key == game.GetKey(GlKeys.BackSpace)) { if (StringTools.StringLength(game.platform, game.GuiTypingBuffer) > 0) { game.GuiTypingBuffer = StringTools.StringSubstring(game.platform, game.GuiTypingBuffer, 0, StringTools.StringLength(game.platform, game.GuiTypingBuffer) - 1); } args.SetHandled(true); return; } if (game.keyboardStateRaw[game.GetKey(GlKeys.ControlLeft)] || game.keyboardStateRaw[game.GetKey(GlKeys.ControlRight)]) { if (key == game.GetKey(GlKeys.V)) { if (game.platform.ClipboardContainsText()) { game.GuiTypingBuffer = StringTools.StringAppend(game.platform, game.GuiTypingBuffer, game.platform.ClipboardGetText()); } args.SetHandled(true); return; } } if (key == game.GetKey(GlKeys.Up)) { game.typinglogpos--; if (game.typinglogpos < 0) { game.typinglogpos = 0; } if (game.typinglogpos >= 0 && game.typinglogpos < game.typinglogCount) { game.GuiTypingBuffer = game.typinglog[game.typinglogpos]; } args.SetHandled(true); } if (key == game.GetKey(GlKeys.Down)) { game.typinglogpos++; if (game.typinglogpos > game.typinglogCount) { game.typinglogpos = game.typinglogCount; } if (game.typinglogpos >= 0 && game.typinglogpos < game.typinglogCount) { game.GuiTypingBuffer = game.typinglog[game.typinglogpos]; } if (game.typinglogpos == game.typinglogCount) { game.GuiTypingBuffer = ""; } args.SetHandled(true); } //Handles player name autocomplete in chat if (eKey == game.GetKey(GlKeys.Tab) && game.platform.StringTrim(game.GuiTypingBuffer) != "") { IntRef partsLength = new IntRef(); string[] parts = game.platform.StringSplit(game.GuiTypingBuffer, " ", partsLength); string completed = DoAutocomplete(parts[partsLength.value - 1]); if (completed == "") { //No completion available. Abort. args.SetHandled(true); return; } else if (partsLength.value == 1) { //Part is first word. Format as "<name>: " game.GuiTypingBuffer = StringTools.StringAppend(game.platform, completed, ": "); } else { //Part is not first. Just complete "<name> " parts[partsLength.value - 1] = completed; game.GuiTypingBuffer = StringTools.StringAppend(game.platform, game.platform.StringJoin(parts, " "), " "); } args.SetHandled(true); return; } args.SetHandled(true); return; } }
static float Max3(float a, float b, float c) { return(MathCi.MaxFloat(MathCi.MaxFloat(a, b), c)); }
internal void ProcessPacket(Packet_Server packet) { if (game.packetHandlers[packet.Id] != null) { game.packetHandlers[packet.Id].Handle(game, packet); } switch (packet.Id) { case Packet_ServerIdEnum.ServerIdentification: { string invalidversionstr = game.language.InvalidVersionConnectAnyway(); game.serverGameVersion = packet.Identification.MdProtocolVersion; if (game.serverGameVersion != game.platform.GetGameVersion()) { game.ChatLog("[GAME] Different game versions"); string q = game.platform.StringFormat2(invalidversionstr, game.platform.GetGameVersion(), game.serverGameVersion); game.invalidVersionDrawMessage = q; game.invalidVersionPacketIdentification = packet; } else { game.ProcessServerIdentification(packet); } game.ReceivedMapLength = 0; } break; case Packet_ServerIdEnum.Ping: { game.SendPingReply(); game.ServerInfo.ServerPing.Send(game.platform); } break; case Packet_ServerIdEnum.PlayerPing: { game.ServerInfo.ServerPing.Receive(game.platform); } break; case Packet_ServerIdEnum.LevelInitialize: { game.ChatLog("[GAME] Initialized map loading"); game.ReceivedMapLength = 0; game.InvokeMapLoadingProgress(0, 0, game.language.Connecting()); } break; case Packet_ServerIdEnum.LevelDataChunk: { game.InvokeMapLoadingProgress(packet.LevelDataChunk.PercentComplete, game.ReceivedMapLength, packet.LevelDataChunk.Status); } break; case Packet_ServerIdEnum.LevelFinalize: { game.ChatLog("[GAME] Finished map loading"); } break; case Packet_ServerIdEnum.SetBlock: { int x = packet.SetBlock.X; int y = packet.SetBlock.Y; int z = packet.SetBlock.Z; int type = packet.SetBlock.BlockType; //try { game.SetTileAndUpdate(x, y, z, type); } //catch { Console.WriteLine("Cannot update tile!"); } } break; case Packet_ServerIdEnum.FillArea: { int ax = packet.FillArea.X1; int ay = packet.FillArea.Y1; int az = packet.FillArea.Z1; int bx = packet.FillArea.X2; int by = packet.FillArea.Y2; int bz = packet.FillArea.Z2; int startx = MathCi.MinInt(ax, bx); int endx = MathCi.MaxInt(ax, bx); int starty = MathCi.MinInt(ay, by); int endy = MathCi.MaxInt(ay, by); int startz = MathCi.MinInt(az, bz); int endz = MathCi.MaxInt(az, bz); int blockCount = packet.FillArea.BlockCount; { for (int x = startx; x <= endx; x++) { for (int y = starty; y <= endy; y++) { for (int z = startz; z <= endz; z++) { // if creative mode is off and player run out of blocks if (blockCount == 0) { return; } //try { game.SetTileAndUpdate(x, y, z, packet.FillArea.BlockType); } //catch //{ // Console.WriteLine("Cannot update tile!"); //} blockCount--; } } } } } break; case Packet_ServerIdEnum.FillAreaLimit: { game.fillAreaLimit = packet.FillAreaLimit.Limit; if (game.fillAreaLimit > 100000) { game.fillAreaLimit = 100000; } } break; case Packet_ServerIdEnum.Freemove: { game.AllowFreemove = packet.Freemove.IsEnabled != 0; if (!game.AllowFreemove) { game.controls.SetFreemove(FreemoveLevelEnum.None); game.movespeed = game.basemovespeed; game.Log(game.language.MoveNormal()); } } break; case Packet_ServerIdEnum.PlayerSpawnPosition: { int x = packet.PlayerSpawnPosition.X; int y = packet.PlayerSpawnPosition.Y; int z = packet.PlayerSpawnPosition.Z; game.playerPositionSpawnX = x; game.playerPositionSpawnY = z; game.playerPositionSpawnZ = y; game.Log(game.platform.StringFormat(game.language.SpawnPositionSetTo(), game.platform.StringFormat3("{0},{1},{2}", game.platform.IntToString(x), game.platform.IntToString(y), game.platform.IntToString(z)))); } break; case Packet_ServerIdEnum.Message: { game.AddChatline(packet.Message.Message); game.ChatLog(packet.Message.Message); } break; case Packet_ServerIdEnum.DisconnectPlayer: { game.ChatLog(game.platform.StringFormat("[GAME] Disconnected by the server ({0})", packet.DisconnectPlayer.DisconnectReason)); //Exit mouse pointer lock if necessary if (game.platform.IsMousePointerLocked()) { game.platform.ExitMousePointerLock(); } //When server disconnects player, return to main menu game.platform.MessageBoxShowError(packet.DisconnectPlayer.DisconnectReason, "Disconnected from server"); game.ExitToMainMenu_(); break; } case Packet_ServerIdEnum.PlayerStats: { Packet_ServerPlayerStats p = packet.PlayerStats; game.PlayerStats = p; } break; case Packet_ServerIdEnum.FiniteInventory: { //check for null so it's possible to connect //to old versions of game (before 2011-05-05) if (packet.Inventory.Inventory != null) { //d_Inventory.CopyFrom(ConvertInventory(packet.Inventory.Inventory)); game.UseInventory(packet.Inventory.Inventory); } //FiniteInventory = packet.FiniteInventory.BlockTypeAmount; //ENABLE_FINITEINVENTORY = packet.FiniteInventory.IsFinite; //FiniteInventoryMax = packet.FiniteInventory.Max; } break; case Packet_ServerIdEnum.Season: { packet.Season.Hour -= 1; if (packet.Season.Hour < 0) { //shouldn't happen packet.Season.Hour = 12 * Game.HourDetail; } int sunlight = game.NightLevels[packet.Season.Hour]; game.SkySphereNight = sunlight < 8; game.d_SunMoonRenderer.day_length_in_seconds = 60 * 60 * 24 / packet.Season.DayNightCycleSpeedup; int hour = packet.Season.Hour / Game.HourDetail; if (game.d_SunMoonRenderer.GetHour() != hour) { game.d_SunMoonRenderer.SetHour(hour); } if (game.sunlight_ != sunlight) { game.sunlight_ = sunlight; //d_Shadows.ResetShadows(); game.RedrawAllBlocks(); } } break; case Packet_ServerIdEnum.BlobInitialize: { game.blobdownload = new CitoMemoryStream(); //blobdownloadhash = ByteArrayToString(packet.BlobInitialize.hash); game.blobdownloadname = packet.BlobInitialize.Name; game.blobdownloadmd5 = packet.BlobInitialize.Md5; } break; case Packet_ServerIdEnum.BlobPart: { int length = game.platform.ByteArrayLength(packet.BlobPart.Data); game.blobdownload.Write(packet.BlobPart.Data, 0, length); game.ReceivedMapLength += length; } break; case Packet_ServerIdEnum.BlobFinalize: { byte[] downloaded = game.blobdownload.ToArray(); if (game.blobdownloadname != null) // old servers { game.SetFile(game.blobdownloadname, game.blobdownloadmd5, downloaded, game.blobdownload.Length()); } game.blobdownload = null; } break; case Packet_ServerIdEnum.Sound: { game.PlaySoundAt(packet.Sound.Name, packet.Sound.X, packet.Sound.Y, packet.Sound.Z); } break; case Packet_ServerIdEnum.RemoveMonsters: { for (int i = Game.entityMonsterIdStart; i < Game.entityMonsterIdStart + Game.entityMonsterIdCount; i++) { game.entities[i] = null; } } break; case Packet_ServerIdEnum.Translation: game.language.Override(packet.Translation.Lang, packet.Translation.Id, packet.Translation.Translation); break; case Packet_ServerIdEnum.BlockType: game.NewBlockTypes[packet.BlockType.Id] = packet.BlockType.Blocktype; break; case Packet_ServerIdEnum.SunLevels: game.NightLevels = packet.SunLevels.Sunlevels; break; case Packet_ServerIdEnum.LightLevels: for (int i = 0; i < packet.LightLevels.LightlevelsCount; i++) { game.mLightLevels[i] = game.DeserializeFloat(packet.LightLevels.Lightlevels[i]); } break; case Packet_ServerIdEnum.Follow: IntRef oldFollowId = game.FollowId(); game.Follow = packet.Follow.Client; if (packet.Follow.Tpp != 0) { game.SetCamera(CameraType.Overhead); game.player.position.rotx = Game.GetPi(); game.GuiStateBackToGame(); } else { game.SetCamera(CameraType.Fpp); } break; case Packet_ServerIdEnum.Bullet: game.EntityAddLocal(game.CreateBulletEntity( game.DeserializeFloat(packet.Bullet.FromXFloat), game.DeserializeFloat(packet.Bullet.FromYFloat), game.DeserializeFloat(packet.Bullet.FromZFloat), game.DeserializeFloat(packet.Bullet.ToXFloat), game.DeserializeFloat(packet.Bullet.ToYFloat), game.DeserializeFloat(packet.Bullet.ToZFloat), game.DeserializeFloat(packet.Bullet.SpeedFloat))); break; case Packet_ServerIdEnum.Ammo: if (!game.ammostarted) { game.ammostarted = true; for (int i = 0; i < packet.Ammo.TotalAmmoCount; i++) { Packet_IntInt k = packet.Ammo.TotalAmmo[i]; game.LoadedAmmo[k.Key_] = MathCi.MinInt(k.Value_, game.blocktypes[k.Key_].AmmoMagazine); } } game.TotalAmmo = new int[GlobalVar.MAX_BLOCKTYPES]; for (int i = 0; i < packet.Ammo.TotalAmmoCount; i++) { game.TotalAmmo[packet.Ammo.TotalAmmo[i].Key_] = packet.Ammo.TotalAmmo[i].Value_; } break; case Packet_ServerIdEnum.Explosion: { Entity entity = new Entity(); entity.expires = new Expires(); entity.expires.timeLeft = game.DeserializeFloat(packet.Explosion.TimeFloat); entity.push = packet.Explosion; game.EntityAddLocal(entity); } break; case Packet_ServerIdEnum.Projectile: { Entity entity = new Entity(); Sprite sprite = new Sprite(); sprite.image = "ChemicalGreen.png"; sprite.size = 14; sprite.animationcount = 0; sprite.positionX = game.DeserializeFloat(packet.Projectile.FromXFloat); sprite.positionY = game.DeserializeFloat(packet.Projectile.FromYFloat); sprite.positionZ = game.DeserializeFloat(packet.Projectile.FromZFloat); entity.sprite = sprite; Grenade_ grenade = new Grenade_(); grenade.velocityX = game.DeserializeFloat(packet.Projectile.VelocityXFloat); grenade.velocityY = game.DeserializeFloat(packet.Projectile.VelocityYFloat); grenade.velocityZ = game.DeserializeFloat(packet.Projectile.VelocityZFloat); grenade.block = packet.Projectile.BlockId; grenade.sourcePlayer = packet.Projectile.SourcePlayerID; entity.grenade = grenade; entity.expires = Expires.Create(game.DeserializeFloat(packet.Projectile.ExplodesAfterFloat)); game.EntityAddLocal(entity); } break; case Packet_ServerIdEnum.BlockTypes: game.blocktypes = game.NewBlockTypes; game.NewBlockTypes = new Packet_BlockType[GlobalVar.MAX_BLOCKTYPES]; int textureInAtlasIdsCount = 1024; string[] textureInAtlasIds = new string[textureInAtlasIdsCount]; int lastTextureId = 0; for (int i = 0; i < GlobalVar.MAX_BLOCKTYPES; i++) { if (game.blocktypes[i] != null) { string[] to_load = new string[7]; int to_loadLength = 7; { to_load[0] = game.blocktypes[i].TextureIdLeft; to_load[1] = game.blocktypes[i].TextureIdRight; to_load[2] = game.blocktypes[i].TextureIdFront; to_load[3] = game.blocktypes[i].TextureIdBack; to_load[4] = game.blocktypes[i].TextureIdTop; to_load[5] = game.blocktypes[i].TextureIdBottom; to_load[6] = game.blocktypes[i].TextureIdForInventory; } for (int k = 0; k < to_loadLength; k++) { if (!Contains(textureInAtlasIds, textureInAtlasIdsCount, to_load[k])) { textureInAtlasIds[lastTextureId++] = to_load[k]; } } } } game.d_Data.UseBlockTypes(game.platform, game.blocktypes, GlobalVar.MAX_BLOCKTYPES); for (int i = 0; i < GlobalVar.MAX_BLOCKTYPES; i++) { Packet_BlockType b = game.blocktypes[i]; if (b == null) { continue; } //Indexed by block id and TileSide. if (textureInAtlasIds != null) { game.TextureId[i][0] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdTop); game.TextureId[i][1] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdBottom); game.TextureId[i][2] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdFront); game.TextureId[i][3] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdBack); game.TextureId[i][4] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdLeft); game.TextureId[i][5] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdRight); game.TextureIdForInventory[i] = IndexOf(textureInAtlasIds, textureInAtlasIdsCount, b.TextureIdForInventory); } } game.UseTerrainTextures(textureInAtlasIds, textureInAtlasIdsCount); game.handRedraw = true; game.RedrawAllBlocks(); break; case Packet_ServerIdEnum.ServerRedirect: game.ChatLog("[GAME] Received server redirect"); //Leave current server game.SendLeave(Packet_LeaveReasonEnum.Leave); //Exit game screen and create new game instance game.ExitAndSwitchServer(packet.Redirect); break; } }
public override void OnKeyDown(Game game_, KeyEventArgs args) { if (game.guistate != GuiState.Normal) { //Don't open chat when not in normal game return; } int eKey = args.GetKeyCode(); if (eKey == game.GetKey(GlKeys.Number7) && game.IsShiftPressed && game.GuiTyping == TypingState.None) // don't need to hit enter for typing commands starting with slash { game.GuiTyping = TypingState.Typing; game.IsTyping = true; game.GuiTypingBuffer = ""; game.IsTeamchat = false; args.SetHandled(true); return; } if (eKey == game.GetKey(GlKeys.PageUp) && game.GuiTyping == TypingState.Typing) { ChatPageScroll++; args.SetHandled(true); } if (eKey == game.GetKey(GlKeys.PageDown) && game.GuiTyping == TypingState.Typing) { ChatPageScroll--; args.SetHandled(true); } ChatPageScroll = MathCi.ClampInt(ChatPageScroll, 0, game.ChatLinesCount / ChatLinesMaxToDraw); if (eKey == game.GetKey(GlKeys.Enter) || eKey == game.GetKey(GlKeys.KeypadEnter)) { if (game.GuiTyping == TypingState.Typing) { game.typinglog[game.typinglogCount++] = game.GuiTypingBuffer; game.typinglogpos = game.typinglogCount; game.ClientCommand(game.GuiTypingBuffer); game.GuiTypingBuffer = ""; game.IsTyping = false; game.GuiTyping = TypingState.None; game.platform.ShowKeyboard(false); } else if (game.GuiTyping == TypingState.None) { game.StartTyping(); } else if (game.GuiTyping == TypingState.Ready) { game.platform.ConsoleWriteLine("Keyboard_KeyDown ready"); } args.SetHandled(true); return; } if (game.GuiTyping == TypingState.Typing) { int key = eKey; if (key == game.GetKey(GlKeys.BackSpace)) { if (StringTools.StringLength(game.platform, game.GuiTypingBuffer) > 0) { game.GuiTypingBuffer = StringTools.StringSubstring(game.platform, game.GuiTypingBuffer, 0, StringTools.StringLength(game.platform, game.GuiTypingBuffer) - 1); } args.SetHandled(true); return; } if (game.keyboardStateRaw[game.GetKey(GlKeys.ControlLeft)] || game.keyboardStateRaw[game.GetKey(GlKeys.ControlRight)]) { if (key == game.GetKey(GlKeys.V)) { if (game.platform.ClipboardContainsText()) { game.GuiTypingBuffer = StringTools.StringAppend(game.platform, game.GuiTypingBuffer, game.platform.ClipboardGetText()); } args.SetHandled(true); return; } } if (key == game.GetKey(GlKeys.Up)) { game.typinglogpos--; if (game.typinglogpos < 0) { game.typinglogpos = 0; } if (game.typinglogpos >= 0 && game.typinglogpos < game.typinglogCount) { game.GuiTypingBuffer = game.typinglog[game.typinglogpos]; } args.SetHandled(true); } if (key == game.GetKey(GlKeys.Down)) { game.typinglogpos++; if (game.typinglogpos > game.typinglogCount) { game.typinglogpos = game.typinglogCount; } if (game.typinglogpos >= 0 && game.typinglogpos < game.typinglogCount) { game.GuiTypingBuffer = game.typinglog[game.typinglogpos]; } if (game.typinglogpos == game.typinglogCount) { game.GuiTypingBuffer = ""; } args.SetHandled(true); } args.SetHandled(true); return; } }
internal void InterpolatePositions(Game game, float dt) { for (int i = 0; i < game.entitiesCount; i++) { Entity e = game.entities[i]; if (e == null) { continue; } if (e.networkPosition == null) { continue; } if (i == game.LocalPlayerId) { continue; } if (!e.networkPosition.PositionLoaded) { continue; } if (e.playerDrawInfo == null) { e.playerDrawInfo = new PlayerDrawInfo(); } if (e.playerDrawInfo.interpolation == null) { NetworkInterpolation n = new NetworkInterpolation(); PlayerInterpolate playerInterpolate = new PlayerInterpolate(); playerInterpolate.platform = game.platform; n.req = playerInterpolate; n.DELAYMILLISECONDS = 500; n.EXTRAPOLATE = false; n.EXTRAPOLATION_TIMEMILLISECONDS = 300; e.playerDrawInfo.interpolation = n; } e.playerDrawInfo.interpolation.DELAYMILLISECONDS = MathCi.MaxInt(100, game.ServerInfo.ServerPing.RoundtripTimeTotalMilliseconds()); Entity p = e; PlayerDrawInfo info = p.playerDrawInfo; float networkposX = p.networkPosition.x; float networkposY = p.networkPosition.y; float networkposZ = p.networkPosition.z; if ((!game.Vec3Equal(networkposX, networkposY, networkposZ, info.lastnetworkposX, info.lastnetworkposY, info.lastnetworkposZ)) || p.networkPosition.rotx != info.lastnetworkrotx || p.networkPosition.roty != info.lastnetworkroty || p.networkPosition.rotz != info.lastnetworkrotz) { PlayerInterpolationState state = new PlayerInterpolationState(); state.positionX = networkposX; state.positionY = networkposY; state.positionZ = networkposZ; state.rotx = p.networkPosition.rotx; state.roty = p.networkPosition.roty; state.rotz = p.networkPosition.rotz; info.interpolation.AddNetworkPacket(state, game.totaltimeMilliseconds); } PlayerInterpolationState curstate = game.platform.CastToPlayerInterpolationState(info.interpolation.InterpolatedState(game.totaltimeMilliseconds)); if (curstate == null) { curstate = new PlayerInterpolationState(); } //do not interpolate player position if player is controlled by game world if (game.EnablePlayerUpdatePositionContainsKey(i) && !game.EnablePlayerUpdatePosition(i)) { curstate.positionX = p.networkPosition.x; curstate.positionY = p.networkPosition.y; curstate.positionZ = p.networkPosition.z; } float curposX = curstate.positionX; float curposY = curstate.positionY; float curposZ = curstate.positionZ; info.velocityX = curposX - info.lastcurposX; info.velocityY = curposY - info.lastcurposY; info.velocityZ = curposZ - info.lastcurposZ; info.moves = (!game.Vec3Equal(curposX, curposY, curposZ, info.lastcurposX, info.lastcurposY, info.lastcurposZ)); info.lastcurposX = curposX; info.lastcurposY = curposY; info.lastcurposZ = curposZ; info.lastnetworkposX = networkposX; info.lastnetworkposY = networkposY; info.lastnetworkposZ = networkposZ; info.lastnetworkrotx = p.networkPosition.rotx; info.lastnetworkroty = p.networkPosition.roty; info.lastnetworkrotz = p.networkPosition.rotz; p.position.x = curposX; p.position.y = curposY; p.position.z = curposZ; p.position.rotx = curstate.rotx; p.position.roty = curstate.roty; p.position.rotz = curstate.rotz; } }
/// <summary> /// Creates a bitmap from a given string /// </summary> /// <param name="t">The <see cref="Text_"/> object to create an image from</param> /// <returns>A <see cref="BitmapCi"/> containing the rendered text</returns> internal BitmapCi CreateTextTexture(Text_ t) { IntRef partsCount = new IntRef(); TextPart[] parts = DecodeColors(t.text, t.color, partsCount); float totalwidth = 0; float totalheight = 0; int[] sizesX = new int[partsCount.value]; int[] sizesY = new int[partsCount.value]; for (int i = 0; i < partsCount.value; i++) { IntRef outWidth = new IntRef(); IntRef outHeight = new IntRef(); platform.TextSize(parts[i].text, t.font, outWidth, outHeight); sizesX[i] = outWidth.value; sizesY[i] = outHeight.value; totalwidth += outWidth.value; totalheight = MathCi.MaxFloat(totalheight, outHeight.value); } int size2X = NextPowerOfTwo(platform.FloatToInt(totalwidth) + 1); int size2Y = NextPowerOfTwo(platform.FloatToInt(totalheight) + 1); BitmapCi bmp2 = platform.BitmapCreate(size2X, size2Y); int[] bmp2Pixels = new int[size2X * size2Y]; float currentwidth = 0; for (int i = 0; i < partsCount.value; i++) { int sizeiX = sizesX[i]; int sizeiY = sizesY[i]; if (sizeiX == 0 || sizeiY == 0) { continue; } Text_ partText = new Text_(); partText.text = parts[i].text; partText.color = parts[i].color; partText.font = t.font; BitmapCi partBmp = platform.CreateTextTexture(partText); int partWidth = platform.FloatToInt(platform.BitmapGetWidth(partBmp)); int partHeight = platform.FloatToInt(platform.BitmapGetHeight(partBmp)); int[] partBmpPixels = new int[partWidth * partHeight]; platform.BitmapGetPixelsArgb(partBmp, partBmpPixels); for (int x = 0; x < partWidth; x++) { for (int y = 0; y < partHeight; y++) { if (x + currentwidth >= size2X) { continue; } if (y >= size2Y) { continue; } int c = partBmpPixels[MapUtilCi.Index2d(x, y, partWidth)]; if (Game.ColorA(c) > 0) { bmp2Pixels[MapUtilCi.Index2d(platform.FloatToInt(currentwidth) + x, y, size2X)] = c; } } } currentwidth += sizeiX; } platform.BitmapSetPixelsArgb(bmp2, bmp2Pixels); return(bmp2); }