DanisRace/Scripts/Multiplayer_Client.py~

154 lines
3.8 KiB
Python
Raw Permalink Normal View History

2024-08-27 14:34:26 +02:00
# GPLv3 or later
# (C) J.Y.Amihud ( blenderdumbass ) 2024
# Multiplayer client functions
import bge
import time
import json
import zlib
from Scripts import Vehicle
from Scripts import Character_Controll
from Scripts import Opt
from Scripts import Settings
from Scripts.Multiplayer_Shared import *
from Scripts import Reuse
from Scripts.Common import *
settings = Settings.load_settings()
host = settings.get("mp-host", "")
def DescribeScene():
scene = bge.logic.getCurrentScene()
dani = scene.objects["Dani_Box"]
cam = scene.active_camera
chunksize = 250
data = {}
addr = Opt.Address(dani.position, chunksize)
if addr not in data:
data[addr] = []
danidata = Character_Controll.Encode(dani)
data[addr].append(danidata)
for car in bge.logic.globalDict["allcars"]:
if car.get("inview"):
addr = Opt.Address(car.position, chunksize)
cardata = Vehicle.Encode(car)
if addr not in data:
data[addr] = []
data[addr].append(cardata)
return data
def MainLoop():
scene = bge.logic.getCurrentScene()
dani = scene.objects["Dani_Box"]
cam = scene.active_camera
chunksize = 250
while True:
try:
# Testing if the game is still runing.
# it will fail when the game engine stops.
try: bge.logic.getRealTime()
except: return
# A bit of delay, to not owerwhelm the server
time.sleep(0.2)
######### SENDING THE DATA TO SERVER ############
data = {}
# Login
LoginEncode(data)
# Scene
data["scene"] = DescribeScene()
data["vision"] = Opt.Surround(cam.position,
chunksize,
cam.orientation.to_euler())
######### DEALING WITH RESPONSE ############
data = Send(host, data)
for key in data:
payload = data[key]
if key == "login":
LoginDecode(payload)
elif key == "scene":
SceneDecode(payload)
else:
print(key, payload)
except Exception as e:
print(clr["tdrd"], e, clr["norm"])
def LoginEncode(data):
data["login"] = {}
data["login"]["userId"] = bge.logic.globalDict.get("userId")
data["login"]["username"] = settings.get("mp-name")
data["login"]["room"] = settings.get("mp-room")
def LoginDecode(data):
if data.get("userId"):
bge.logic.globalDict["userId"] = data["userId"]
def SceneDecode(data):
netObjects = bge.logic.globalDict["netObjects"]
if not data:
return
for addr in data:
chunk = data[addr]
for obj in chunk:
# Sometimes we want to update some things like netId.
if obj.get("ID") in netObjects["pythonId"]\
and obj.get("name") == netObjects["pythonId"][obj["ID"]].name:
netObjects["pythonId"][obj["ID"]]["netId"] = obj.get("netId")
else:
if obj.get("type") == "veh":
Vehicle.Decode(obj)
# elif obj.get("netId") not in netObjects["netId"]:
# try:
# OBJ = Reuse.Create(obj.get("name"))
# except:
# OBJ = Reuse.Create("MoriaBox")
# netObjects["netId"][obj.get("netId")] = OBJ
# OBJ = netObjects["netId"][obj.get("netId")]
# OBJ.position = obj.get("position", (0,0,0))
# OBJ.orientation = obj.get("orientation", (0,0,0))