Skip to content

Commit

Permalink
feat: add realistic broadcasting (throttle)
Browse files Browse the repository at this point in the history
  • Loading branch information
anilmisirlioglu committed Feb 8, 2022
1 parent 6c5c313 commit 8fd5e7e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
32 changes: 32 additions & 0 deletions internal/udp/header.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package udp

import (
"bytes"
"encoding/binary"
)

type Header struct {
PacketFormat uint16 // 2021
GameMajorVersion uint8 // Game major version - "X.00"
GameMinorVersion uint8 // Game minor version - "1.XX"
PacketVersion uint8 // Version of this packet type, all start from 1
PacketID uint8 // Identifier for the packet type, see below
SessionUID uint64 // Unique identifier for the session
SessionTime float32 // Session timestamp
FrameIdentifier uint32 // Identifier for the frame the data was retrieved on
PlayerCarIndex uint8 // Index of player's car in the array
SecondaryPlayerCarIndex uint8 // Index of secondary player's car in the array (split screen)
}

func (h *Header) Read(buf []byte) error {
reader := bytes.NewReader(buf)
if err := binary.Read(reader, binary.LittleEndian, h); err != nil {
return err
}

return nil
}

func (h *Header) Second() int32 {
return int32(h.SessionTime)
}
15 changes: 15 additions & 0 deletions pkg/broadcaster/broadcaster.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"net"
"os"
"time"
)

type Broadcaster struct {
Expand Down Expand Up @@ -48,6 +49,7 @@ func (b *Broadcaster) Start(file string) error {
defer f.Close()

offset := int64(0)
t := 0
for {
select {
case <-b.ctx.Done():
Expand All @@ -70,6 +72,19 @@ func (b *Broadcaster) Start(file string) error {

offset += int64(n)

header := new(udp.Header)
if header.Read(buf) != nil {
if opts.Verbose {
printer.PrintError("header read error: %s", err.Error())
}
}

d := int(header.SessionTime * 100000)
if d != t {
time.Sleep(time.Nanosecond * time.Duration(d))
t = d
}

err = b.serv.WriteSocket(buf)
if err != nil {
if opts.Verbose {
Expand Down

0 comments on commit 8fd5e7e

Please sign in to comment.