From 465f9d8d24d3d7ab7aab2a3784c53cd5ad208e51 Mon Sep 17 00:00:00 2001 From: Kestred Date: Sun, 21 Sep 2014 16:01:07 -0700 Subject: [PATCH 01/33] Implement poll_datagram (non-blocking receive) in Connection. --- astron/connection.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/astron/connection.py b/astron/connection.py index 8c37de7..e25d3ef 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -1,3 +1,4 @@ +import errno import struct import socket from bamboo.wire import Datagram @@ -33,6 +34,22 @@ def recv_datagram(self): return dg def poll_datagram(self): + self.socket.setblocking(0) + try: + length = struct.unpack(' Date: Sun, 21 Sep 2014 16:06:51 -0700 Subject: [PATCH 02/33] Cleanup: Remove forgotten (unreachable) raise. --- astron/connection.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/astron/connection.py b/astron/connection.py index e25d3ef..1712581 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -49,10 +49,6 @@ def poll_datagram(self): dg.add_data(data) return dg - - "Receive a datagram if immediately available, otherwise return None." - raise NotImplementedError - def _read(self, length): result = '' while len(result) < length: From 84770e8a2a25d1380e89e37ca942eed618b42d94 Mon Sep 17 00:00:00 2001 From: Kestred Date: Sun, 21 Sep 2014 16:21:38 -0700 Subject: [PATCH 03/33] Bugfix: Fix syntax errors using `example.py` --- astron/connection.py | 2 +- astron/object_repository.py | 9 +++++---- astrond.yml | 11 +++++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 astrond.yml diff --git a/astron/connection.py b/astron/connection.py index 1712581..7a61e6d 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -23,7 +23,7 @@ def is_connected(self): def send_datagram(self, datagram): msg = struct.pack(' Date: Sun, 21 Sep 2014 16:58:45 -0700 Subject: [PATCH 04/33] Bugfix: Other typo fixes. --- astron/connection.py | 4 ++-- astron/object_repository.py | 2 +- astrond.yml | 4 +++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/astron/connection.py b/astron/connection.py index 7a61e6d..9725e02 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -27,7 +27,7 @@ def send_datagram(self, datagram): def recv_datagram(self): """Wait for the next datagram and return it.""" - length = struct.unpack(' Date: Sun, 21 Sep 2014 17:01:50 -0700 Subject: [PATCH 05/33] Bugfix: Properly poll repeatedly in poll_forever() --- astron/object_repository.py | 1 + 1 file changed, 1 insertion(+) diff --git a/astron/object_repository.py b/astron/object_repository.py index 0bff99e..6ae1881 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -56,6 +56,7 @@ def poll_forever(self): dg = self.recv_datagram() while dg is not None: self._handle_datagram(dg) + dg = self.recv_datagram() except socket.error: return From 8050b3d0a608607b1cfacb3095043c2841347efe Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Tue, 21 Oct 2014 02:10:53 +0200 Subject: [PATCH 06/33] Errr... Chaos? --- astron/connection.py | 2 + astron/distributed_object.py | 83 +++++++- astron/object_repository.py | 58 +++--- example/example.py | 8 + example.py => example/example_main.py | 2 +- example/transitional/example_main.py | 32 +++ .../transitional/simple_example.dc | 2 +- example/transitional/simple_example.py | 186 ++++++++++++++++++ 8 files changed, 345 insertions(+), 28 deletions(-) create mode 100644 example/example.py rename example.py => example/example_main.py (90%) create mode 100755 example/transitional/example_main.py rename simple_example.dc => example/transitional/simple_example.dc (94%) create mode 100644 example/transitional/simple_example.py diff --git a/astron/connection.py b/astron/connection.py index ccc6a72..92e9790 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -12,6 +12,8 @@ def __init__(self): def connect(self, host='127.0.0.1', port=7199, connect_timeout=None): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.settimeout(connect_timeout) + # FIXME: Handle this! + # socket.error: [Errno 111] Connection refused self.socket.connect((host, port)) self.socket.setblocking(0) self.socket.settimeout(None) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 81d6d2c..16daaa3 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -1,9 +1,30 @@ +from bamboo import module +from bamboo.wire import Datagram +from pprint import pprint +from astron.client_messages import CLIENT_OBJECT_SET_FIELD + class DistributedObject: - def __init__(self, repository, do_id, parent_id, zone_id): + def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): self.repo = repository + self.dclass_id = dclass_id + self.dclass = self.repo.mod.get_class(dclass_id) + self.dmethod_name_to_id = dict([(self.dclass.get_field(dmethod_id).name(), dmethod_id) + for dmethod_id in range(0, self.dclass.num_fields())]) self.do_id = do_id self.parent = parent_id self.zone = zone_id + self.type_packer = {module.kTypeInt8: self.pack_int8, + module.kTypeInt16: self.pack_int16, + module.kTypeInt32: self.pack_int32, + module.kTypeInt64: self.pack_int64, + module.kTypeFloat32: self.pack_float32, + module.kTypeFloat64: self.pack_float64, + module.kTypeChar: self.pack_char, + module.kTypeString: self.pack_string, + module.kTypeVarstring: self.pack_string, + } + # FIXME: Remove after debugging + #pprint(self.type_packer) def init(self): print("DO created: %d" % (self.do_id, )) @@ -11,6 +32,62 @@ def init(self): def delete(self): print("DO deleted: %d" % (self.do_id, )) - def send_update(self, field_name, value): - # FIXME: Find field type, write datagram, send + def call_dist_method(self, name, *args): pass + + def send_update(self, field_name, *values): + dmethod_id = self.dmethod_name_to_id[field_name] + field = self.dclass.get_field(dmethod_id) + num_args = field.type().as_method().num_parameters() + if num_args != len(values): + print("Distributed method %s requires %d args, %d were provided" % (field_name, num_args, len(values))) + else: + dg = Datagram() + dg.add_int16(CLIENT_OBJECT_SET_FIELD) + dg.add_int32(self.do_id) + dg.add_int16(dmethod_id) + for arg_id in range(0, num_args): + arg = field.type().as_method().get_parameter(arg_id) + arg_type = arg.type().subtype() + if arg_type == module.kTypeStruct: + self.pack_struct(dg, arg.type().as_struct(), *values[arg_id]) + else: + self.type_packer[arg_type](dg, values[arg_id]) + self.repo.send_datagram(dg) + + def pack_struct(self, dg, struct, *values): + num_args = struct.num_fields() + if num_args != len(values): + print("Struct %s requires %d args, %d were provided" % (struct.name(), num_args, len(values))) + else: + for arg_id in range(0, num_args): + arg = struct.get_field(arg_id) + arg_type = arg.type().subtype() + if arg_type == module.kTypeStruct: + self.pack_struct(dg, arg.type().as_struct(), *values[arg_id]) + else: + self.type_packer[arg_type](dg, values[arg_id]) + + def pack_int8(self, dg, value): + dg.add_uint8(value) + + def pack_int16(self, dg, value): + dg.add_uint16(value) + + def pack_int32(self, dg, value): + dg.add_uint32(value) + + def pack_int64(self, dg, value): + dg.add_uint64(value) + + def pack_float32(self, dg, value): + dg.add_float32(value) + + def pack_float64(self, dg, value): + dg.add_float64(value) + + def pack_char(self, dg, value): + dg.add_char(value) + + def pack_string(self, dg, value): + dg.add_string(value) diff --git a/astron/object_repository.py b/astron/object_repository.py index 5dd7b58..69e5d91 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -31,24 +31,11 @@ def __init__(self, dcfilename=default_dcfilename): for word in astron_keywords: self.mod.add_keyword(word) dcfile.parse_dcfile(self.mod, dcfilename) - self.dclass_id_to_cls = {} - self.dclass_name_to_cls = {} - for i_id in range(0, self.mod.num_imports()): - # Determine and import the module - dc_module = self.mod.get_import(i_id).module - for symbol in self.mod.get_import(i_id).symbols: - # Figure out the names of used classes - fragments = symbol.split('/') - base_class = fragments[0] - postfixes = fragments[1:] + [''] - for postfix in postfixes: - #cls = importlib.import_module(dc_module, base_class + postfix) - cls = 'the_class' - self.dclass_id_to_cls[(i_id, postfix)] = cls - self.dclass_name_to_cls[base_class + postfix] = cls - pprint(self.dclass_id_to_cls) - pprint(self.dclass_name_to_cls) - + # Create class definition dicts + self.create_dclass_dicts() + # FIXME: Remove this after debugging + #pprint(self.dclass_id_to_cls) + #pprint(self.dclass_name_to_cls) self.handlers = {} @@ -56,6 +43,30 @@ def __init__(self, dcfilename=default_dcfilename): self.interest_counters = {} self.interest_callback_map = {} + def create_dclass_dicts(self): + self.dclass_id_to_cls = {} # (, 'PF'): + self.dclass_id_to_name = {} # (, 'PF'): 'DClass' + self.dclass_name_to_id = {} # 'DClassPF' : , ('DClass', 'PF') : + self.dclass_name_to_cls = {} # 'DClassPF' : , ('DClass', 'PF') : + for dclass_id in range(0, self.mod.num_imports()): + # Determine and import the module + dclass_module_name = self.mod.get_import(dclass_id).module + dclass_module = importlib.import_module(dclass_module_name) + for symbol in self.mod.get_import(dclass_id).symbols: + # Figure out the names of used classes + fragments = str(symbol).split('/') + base_class = fragments[0] + postfixes = fragments[1:] + [''] + for postfix in postfixes: + #print(dclass_module, base_class + postfix) + cls = getattr(dclass_module, base_class + postfix) + self.dclass_id_to_cls[(dclass_id, postfix)] = cls + self.dclass_id_to_name[(dclass_id, postfix)] = base_class + self.dclass_name_to_id[base_class + postfix] = dclass_id + self.dclass_name_to_id[(base_class, postfix)] = dclass_id + self.dclass_name_to_cls[base_class + postfix] = cls + self.dclass_name_to_cls[(base_class, postfix)] = cls + def poll_till_empty(self): """Process all received messages. @@ -80,7 +91,6 @@ def poll_till_empty(self): except EOFError: return False - def poll_forever(self): """Blocks until connection is lost. Processes datagrams as they come in. Be sure to call this in a dedicated thread.""" @@ -108,15 +118,17 @@ def create_view_from_datagram(self, dgi, cls_postfix = ''): # Create the view object cls_name = self.mod.get_class_by_id(dclass_id).get_name() + cls_postfix # FIXME: Get the actual class - cls = DistributedObject - dist_obj = cls(self, do_id, parent_id, zone_id) + # cls = DistributedObject + cls = self.dclass_name_to_cls[cls_name] + dist_obj = cls(self, dclass_id, do_id, parent_id, zone_id) self.distributed_objects[do_id] = dist_obj # FIXME: Read the field values from the dgi and apply them dist_obj.init() def create_view_by_classname(self, cls_name, do_id, parent_id, zone_id): - cls = DistributedObject - dist_obj = cls(self, do_id, parent_id, zone_id) + cls = self.dclass_name_to_cls[cls_name] + dclass_id = self.dclass_name_to_id[cls_name] + dist_obj = cls(self, dclass_id, do_id, parent_id, zone_id) self.distributed_objects[do_id] = dist_obj # FIXME: Read the field values from the dgi and apply them dist_obj.init() diff --git a/example/example.py b/example/example.py new file mode 100644 index 0000000..8823f45 --- /dev/null +++ b/example/example.py @@ -0,0 +1,8 @@ +from astron.distributed_object import DistributedObject + +class LoginManager(DistributedObject): + pass + +class LoginManagerUD(DistributedObject): + pass + diff --git a/example.py b/example/example_main.py similarity index 90% rename from example.py rename to example/example_main.py index 2af2f43..375ab94 100755 --- a/example.py +++ b/example/example_main.py @@ -5,7 +5,7 @@ from astron.object_repository import ClientRepository if __name__ == '__main__': - repo = ClientRepository('SimpleExample v0.2', 'simple_example.dc') + repo = ClientRepository('SimpleExample v0.2', 'example.dc') def connected(): print('Connection established.') diff --git a/example/transitional/example_main.py b/example/transitional/example_main.py new file mode 100755 index 0000000..2421b08 --- /dev/null +++ b/example/transitional/example_main.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +from time import sleep + +from astron.object_repository import ClientRepository + +if __name__ == '__main__': + repo = ClientRepository('SimpleExample v0.2', 'simple_example.dc') + + def connected(): + print('Connection established.') + login_manager = repo.create_view_by_classname('LoginManager', 1234, 0, 0) + sleep(1) + login_manager.login("guest", "guest") + + def ejected(error_code, reason): + print('Got ejected (%i): %s' % (error_code, reason)) + + def failed(): + print('Connection attempt failed.') + + repo.connect(connected, failed, ejected) + + while True: + repo.poll_till_empty() + #print(repo.poll_datagram()) + sleep(1) + +## Lets do some random things +#print mod.get_num_classes() # or GetNumClasses +#cls = mod.get_class_by_name('Foobar') # or getClassByName +#print cls.get_name() # -> 'Foobar' diff --git a/simple_example.dc b/example/transitional/simple_example.dc similarity index 94% rename from simple_example.dc rename to example/transitional/simple_example.dc index 56662ca..6dff332 100644 --- a/simple_example.dc +++ b/example/transitional/simple_example.dc @@ -26,5 +26,5 @@ dclass DistributedMaproot { // position and heading. dclass DistributedAvatar { setXYZH(int16 / 1000, int16 / 1000, int16 / 1000, int16 / 50) broadcast required; - indicateIntent(int16 / 10, int16 / 10) ownsend airecv; + indicateIntent(int16 / 10, int16 / 10) ownsend airecv; }; diff --git a/example/transitional/simple_example.py b/example/transitional/simple_example.py new file mode 100644 index 0000000..f796327 --- /dev/null +++ b/example/transitional/simple_example.py @@ -0,0 +1,186 @@ +from astron.object_repository import DistributedObject + +from datetime import datetime + +# Constant DO and channel IDs +LoginManagerId = 1234 + +# Game settings +avatar_speed = 3.0 +avatar_rotation_speed = 90.0 + +# ------------------------------------------------------------------- +# LoginManager +# * Registers a DistributedMaproot +# * Authenticates Clients +# * Makes DistributedMaproot create an avatar for new Clients. +# ------------------------------------------------------------------- + +class LoginManager(DistributedObject): + def login(self, username, password): + print("Logging in") + self.send_update("login", username, password) + +class LoginManagerAI(DistributedObject): + def set_maproot(self, maproot_doId): + print(datetime.now().strftime("%H:%M:%S")+" LoginManagerAI.set_maproot("+str(maproot_doId)+") in "+str(self.doId)) + self.sendUpdate("set_maproot", [maproot_doId]) + +class LoginManagerUD(DistributedObject): + def generate(self): + print(datetime.now().strftime("%H:%M:%S")+" LoginManagerUD.generate() for "+str(self.doId)) + + def set_maproot(self, maproot_doId): + """Tells the LoginManagerUD what maproot to notify on login.""" + print(datetime.now().strftime("%H:%M:%S")+" LoginManagerUD.set_maproot("+str(maproot_doId)+") in "+str(self.doId)) + self.maproot = DistributedMaprootUD(self.air) + self.maproot.generateWithRequiredAndId(maproot_doId, 0, 1) + + def login(self, username, password): + clientId = self.air.get_msg_sender() + print(datetime.now().strftime("%H:%M:%S")+" LoginManagerUD.login("+username+", ) in "+str(self.doId)+" for client "+str(clientId)) + if (username == "guest") and (password == "guest"): + # Authenticate a client + # FIXME: "2" is the magic number for CLIENT_STATE_ESTABLISHED, + # for which currently no mapping exists. + self.air.setClientState(clientId, 2) + + # The client is now authenticated; create an Avatar + #self.maproot.sendUpdate("createAvatar", # Field to call + # [clientId]) # Arguments + self.maproot.create_avatar(clientId) + + # log login + self.notify.info("Login successful (user: %s)" % (username,)) + + else: + # Disconnect for bad auth + # FIXME: "122" is the magic number for login problems. + # See https://github.com/Astron/Astron/blob/master/doc/protocol/10-client.md + self.air.eject(clientId, 122, "Bad credentials") + + # log login attempt + self.notify.info("Ejecting client for bad credentials (user: %s)" % (username,)) + +# ------------------------------------------------------------------- +# DistributedMaproot +# * has all avatars in its zone 0 +# * generates new avatars +# ------------------------------------------------------------------- + +#class DistributedMaproot(DistributedObject): +# def generateInit(self): +# print(datetime.now().strftime("%H:%M:%S")+" DistributedMaproot.generateInit() for "+str(self.doId)) + +#class DistributedMaprootOV(DistributedObjectOV): +# def generate(self): +# print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootOV.generate() for "+str(self.doId)) + +class DistributedMaproot(DistributedObject): + pass + +class DistributedMaprootAI(DistributedObject): + def generate(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootAI.generate() for "+str(self.doId)) + + def set_maproot(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootAI.set_maproot() in "+str(self.doId)) + login_manager = self.air.generateGlobalObject(LoginManagerId, 'LoginManager') + login_manager.set_maproot(self.doId) + + def createAvatar(self, clientId): + print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootAI.createAvatar("+str(clientId)+") in "+str(self.doId)) + # Create the avatar + avatar = DistributedAvatarAI(self.air) + avatar.generateWithRequiredAndId(self.air.allocateChannel(), self.getDoId(), 0) # random doId, parentId, zoneId + self.air.setAI(avatar.doId, self.air.ourChannel) + # Set the client to be interested in our zone 0. He can't do + # that himself (or rather: shouldn't be allowed to) as he has + # no visibility of this object. + # We're always using the interest_id 0 because different + # clients use different ID spaces, so why make things more + # complicated? + self.air.clientAddInterest(clientId, 0, self.getDoId(), 0) # client, interest, parent, zone + # Set its owner to the client, upon which in the Clients repo + # magically OV (OwnerView) is generated. + self.air.setOwner(avatar.getDoId(), clientId) + # Declare this to be a session object. + self.air.clientAddSessionObject(clientId, self.getDoId()) + +class DistributedMaprootUD(DistributedObject): + def generate(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootUD.generate() for "+str(self.doId)) + + def create_avatar(self, clientId): + print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootUD.create_avatar("+str(clientId)+") in "+str(self.doId)) + self.sendUpdate("createAvatar", # Field to call + [clientId]) # Arguments + +# ------------------------------------------------------------------- +# DistributedAvatar +# * represents players in the scene graph +# * routes indications of movement intents to AI +# * updates the actual position and orientation +# ------------------------------------------------------------------- + +class DistributedAvatar(DistributedObject): + def generateInit(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatar.generateInit() for "+str(self.doId)) + model = base.loader.loadModel("models/smiley") + model.reparent_to(self) + model.setH(180.0) + # Signal app that this is its avatar + base.messenger.send("distributed_avatar", [self]) + + def delete(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatar.delete() for "+str(self.doId)) + + def setXYZH(self, *args): + DistributedNode.setXYZH(self, *args) + +class DistributedAvatarOV(DistributedObject): + def generateInit(self): + # Make yourself known to the client + print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarOV.generate() for "+str(self.doId)) + base.messenger.send("avatar", [self]) + + def delete(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarOV.delete() for "+str(self.doId)) + + def indicateIntent(self, heading, speed): + self.sendUpdate("indicateIntent", [heading, speed]) + +class DistributedAvatarAI(DistributedObject): + def generate(self, repository=None): + print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarAI.generate() for "+str(self.doId)) + self.heading = 0.0 + self.speed = 0.0 + self.update_task = base.taskMgr.add(self.update_position, "Avatar position update") + + def delete(self): + print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarAI.delete() for "+str(self.doId)) + base.taskMgr.remove(self.update_task) + + def indicateIntent(self, heading, speed): + if (heading < -1.0) or (heading > 1.0) or (speed < -1.0) or (speed > 1.0): + # Client is cheating! + # FIXME: Eject client + return + self.heading = heading + self.speed = speed + + def update_position(self, task): + if (self.heading != 0.0) or (self.speed != 0.0): + dt = globalClock.getDt() + self.setH((self.getH() + self.heading * avatar_rotation_speed * dt) % 360.0) + self.setY(self, self.speed * avatar_speed * dt) + if self.getX() < -10.0: + self.setX(-10.0) + if self.getX() > 10.0: + self.setX(10.0) + if self.getY() < -10.0: + self.setY(-10.0) + if self.getY() > 10.0: + self.setY(10.0) + self.b_setXYZH(self.getX(), self.getY(), self.getZ(), self.getH()) + return Task.cont From d9f815609523c303ab893e1c2147361da411dea8 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Tue, 21 Oct 2014 02:34:12 +0200 Subject: [PATCH 07/33] Fixed connection to astrond. --- example/transitional/example_main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/transitional/example_main.py b/example/transitional/example_main.py index 2421b08..575649c 100755 --- a/example/transitional/example_main.py +++ b/example/transitional/example_main.py @@ -19,7 +19,7 @@ def ejected(error_code, reason): def failed(): print('Connection attempt failed.') - repo.connect(connected, failed, ejected) + repo.connect(connected, failed, ejected, host = '127.0.0.1', port = 6667) while True: repo.poll_till_empty() From bc9fc3dcbc85d50b70cbe6925f44f8d3a706e1ac Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Tue, 21 Oct 2014 03:55:10 +0200 Subject: [PATCH 08/33] Assorted small stuff. --- astron/connection.py | 3 ++- astron/object_repository.py | 9 +++++---- example/transitional/example_main.py | 1 - 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/astron/connection.py b/astron/connection.py index aac3758..ae35345 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -17,7 +17,7 @@ def connect(self, host='127.0.0.1', port=7199, connect_timeout=None): # socket.error: [Errno 111] Connection refused self.socket.connect((host, port)) self.socket.setblocking(0) - self.socket.settimeout(None) + #self.socket.settimeout(None) self._is_connected = True self.reading_message = False self.remaining_length = DATAGRAM_HEADER_SIZE @@ -61,6 +61,7 @@ def poll_datagram(self): def read(self): try: + #print("Blocking: %s" % (str(self.socket.), )) data = self.socket.recv(self.remaining_length) # Has the connection been closed? if len(data) == 0: diff --git a/astron/object_repository.py b/astron/object_repository.py index ebd3adc..4df71fd 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -107,6 +107,7 @@ def poll_forever(self): def handle_datagram(self, dg): dgi = DatagramIterator(dg) msgtype = dgi.read_uint16() + print("Handling %d" % (msgtype, )) if msgtype in self.handlers.keys(): self.handlers[msgtype](dgi) else: @@ -189,7 +190,7 @@ def send_CLIENT_HELLO(self): def send_CLIENT_DISCONNECT(self): dg = Datagram() dg.add_uint16(clientmsg.CLIENT_DISCONNECT) - self.send(dg) + self.send_datagram(dg) # FIXME: The connection should be closed right now. # What about later reads of cached messages? @@ -212,7 +213,7 @@ def send_CLIENT_ADD_INTEREST(self, dg.add_uint16(interest_id) dg.add_uint32(parent_id) dg.add_uint32(zone_id) - self.send(dg) + self.send_datagram(dg) if callback != False: self.interest_callback_map[(interest_id, context_id)] = (callback, callback_args, callback_kwargs) return context_id @@ -239,7 +240,7 @@ def send_CLIENT_ADD_INTEREST_MULTIPLE(self, dg.add_uint16(zone_count) for zone_id in zone_ids: dg.add_uint32(zone_id) - self.send(dg) + self.send_datagram(dg) if callback != False: self.interest_callback_map[(interest_id, context_id)] = (callback, callback_args, callback_kwargs) return context_id @@ -250,7 +251,7 @@ def send_CLIENT_REMOVE_INTEREST(self, interest_id, context_id): dg.add_uint16(clientmsg.CLIENT_REMOVE_INTEREST) dg.add_uint32(context_id) dg.add_uint16(interest_id) - self.send(dg) + self.send_datagram(dg) def send_CLIENT_OBJECT_SET_FIELD(self): # FIXME: Needs signature and implementation diff --git a/example/transitional/example_main.py b/example/transitional/example_main.py index 575649c..4152f58 100755 --- a/example/transitional/example_main.py +++ b/example/transitional/example_main.py @@ -10,7 +10,6 @@ def connected(): print('Connection established.') login_manager = repo.create_view_by_classname('LoginManager', 1234, 0, 0) - sleep(1) login_manager.login("guest", "guest") def ejected(error_code, reason): From d37de908aaf0b74d3e09ae4bdfc694710a579dec Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Wed, 22 Oct 2014 01:31:22 +0200 Subject: [PATCH 09/33] Fixed message polling. Simplified DO creation. Cleanups. --- astron/connection.py | 9 +++++---- astron/distributed_object.py | 2 +- astron/object_repository.py | 5 +---- example/transitional/example_main.py | 7 +------ example/transitional/simple_example.py | 6 ++++++ 5 files changed, 14 insertions(+), 15 deletions(-) diff --git a/astron/connection.py b/astron/connection.py index ae35345..a4e170c 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -17,7 +17,6 @@ def connect(self, host='127.0.0.1', port=7199, connect_timeout=None): # socket.error: [Errno 111] Connection refused self.socket.connect((host, port)) self.socket.setblocking(0) - #self.socket.settimeout(None) self._is_connected = True self.reading_message = False self.remaining_length = DATAGRAM_HEADER_SIZE @@ -41,6 +40,8 @@ def poll_datagram(self): self.read() # Did we just finish reading the message length? if (not self.reading_message) and (self.remaining_length == 0): + # FIXME: Truncate partial data if you have more than needed, you dolt! + # This should be done in read() anyway, why is EVERYTHING read?? length = struct.unpack(' 'Foobar' + sleep(0.1) diff --git a/example/transitional/simple_example.py b/example/transitional/simple_example.py index f796327..c4ce1d3 100644 --- a/example/transitional/simple_example.py +++ b/example/transitional/simple_example.py @@ -124,6 +124,9 @@ def create_avatar(self, clientId): # ------------------------------------------------------------------- class DistributedAvatar(DistributedObject): + def init(self): + print("DistributedAvatar") + def generateInit(self): print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatar.generateInit() for "+str(self.doId)) model = base.loader.loadModel("models/smiley") @@ -139,6 +142,9 @@ def setXYZH(self, *args): DistributedNode.setXYZH(self, *args) class DistributedAvatarOV(DistributedObject): + def init(self): + print("DistributedAvatarOV") + def generateInit(self): # Make yourself known to the client print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarOV.generate() for "+str(self.doId)) From 905c558e02f47433ced26db64c092de621767fb5 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Thu, 23 Oct 2014 04:12:13 +0200 Subject: [PATCH 10/33] Int/UInt packing fixed. --- astron/distributed_object.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 54cab45..dd14fb5 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -17,6 +17,10 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): module.kTypeInt16: self.pack_int16, module.kTypeInt32: self.pack_int32, module.kTypeInt64: self.pack_int64, + module.kTypeUint8: self.pack_uint8, + module.kTypeUint16: self.pack_uint16, + module.kTypeUint32: self.pack_uint32, + module.kTypeUint64: self.pack_uint64, module.kTypeFloat32: self.pack_float32, module.kTypeFloat64: self.pack_float64, module.kTypeChar: self.pack_char, @@ -69,15 +73,27 @@ def pack_struct(self, dg, struct, *values): self.type_packer[arg_type](dg, values[arg_id]) def pack_int8(self, dg, value): - dg.add_uint8(value) + dg.add_int8(value) def pack_int16(self, dg, value): - dg.add_uint16(value) + dg.add_int16(value) def pack_int32(self, dg, value): - dg.add_uint32(value) + dg.add_int32(value) def pack_int64(self, dg, value): + dg.add_int64(value) + + def pack_uint8(self, dg, value): + dg.add_uint8(value) + + def pack_uint16(self, dg, value): + dg.add_uint16(value) + + def pack_uint32(self, dg, value): + dg.add_uint32(value) + + def pack_uint64(self, dg, value): dg.add_uint64(value) def pack_float32(self, dg, value): From 5f374b8a387cbaf6edb0338262b405e0576a8c1d Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sun, 26 Oct 2014 19:12:11 +0100 Subject: [PATCH 11/33] Assorted poking in the dark. --- .gitignore | 1 + astron/connection.py | 1 + astron/distributed_object.py | 7 +- astron/internal_messages.py | 10 +- astron/object_repository.py | 85 +++++++-- example/transitional/astrond.yml | 43 +++++ .../{example_main.py => example_client.py} | 0 example/transitional/example_services.py | 24 +++ example/transitional/example_world.py | 26 +++ example/transitional/simple_example.py | 172 +++--------------- 10 files changed, 199 insertions(+), 170 deletions(-) create mode 100644 example/transitional/astrond.yml rename example/transitional/{example_main.py => example_client.py} (100%) create mode 100755 example/transitional/example_services.py create mode 100755 example/transitional/example_world.py diff --git a/.gitignore b/.gitignore index 48c58e1..9a7415b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .project .pydevproject .gitignore +*.log* diff --git a/astron/connection.py b/astron/connection.py index a4e170c..2c80876 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -24,6 +24,7 @@ def connect(self, host='127.0.0.1', port=7199, connect_timeout=None): def disconnect(self): self.socket.close() + self.is_connected = False def is_connected(self): return self.is_connected diff --git a/astron/distributed_object.py b/astron/distributed_object.py index dd14fb5..2247f29 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -2,6 +2,7 @@ from bamboo.wire import Datagram from pprint import pprint from astron.client_messages import CLIENT_OBJECT_SET_FIELD +from astron.object_repository import MSG_TYPE_CLIENT, MSG_TYPE_INTERNAL class DistributedObject: def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): @@ -46,7 +47,11 @@ def send_update(self, field_name, *values): if num_args != len(values): print("Distributed method %s requires %d args, %d were provided" % (field_name, num_args, len(values))) else: - dg = Datagram() + if self.repo.msg_type == MSG_TYPE_CLIENT: + dg = self.repo.create_message_stub() + else: + # FIXME: If this an AIR object, recipients and sender have to be provided here. + dg = self.repo.create_message_stub() dg.add_int16(CLIENT_OBJECT_SET_FIELD) dg.add_int32(self.do_id) dg.add_int16(dmethod_id) diff --git a/astron/internal_messages.py b/astron/internal_messages.py index e480743..8233e0f 100644 --- a/astron/internal_messages.py +++ b/astron/internal_messages.py @@ -15,13 +15,13 @@ # https://astron.github.io/astron/en/master/12-stateserver.html # StateServer Control -STATESERVER_CREATE_OBJECT_WITH_REQUIRED = 2000 -STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER = 2001 +STATESERVER_CREATE_OBJECT_WITH_REQUIRED = 2000 # -> SS. Create object in SS. it'll then broadcast ENTER_LOCATION +STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER = 2001 # -> SS. Create object in SS. it'll then broadcast ENTER_LOCATION # Distributed Object Control -STATESERVER_DELETE_AI_OBJECTS = 2009 -STATESERVER_OBJECT_GET_FIELD = 2010 -STATESERVER_OBJECT_GET_FIELD_RESP = 2011 +STATESERVER_DELETE_AI_OBJECTS = 2009 # -> SS. Delete all DOs associated with this AI. +STATESERVER_OBJECT_GET_FIELD = 2010 # -> DO. Request value of field. +STATESERVER_OBJECT_GET_FIELD_RESP = 2011 # <- DO. Inform of value of field. STATESERVER_OBJECT_GET_FIELDS = 2012 STATESERVER_OBJECT_GET_FIELDS_RESP = 2013 STATESERVER_OBJECT_GET_ALL = 2014 diff --git a/astron/object_repository.py b/astron/object_repository.py index c0900bf..86da728 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -8,7 +8,6 @@ from connection import Connection import client_messages as clientmsg import internal_messages as servermsg -from distributed_object import DistributedObject import socket import importlib from pprint import pprint @@ -16,6 +15,12 @@ DATAGRAM_SIZE = 2 DATAGRAM_ENCODING = ') in "+str(self.doId)+" for client "+str(clientId)) - if (username == "guest") and (password == "guest"): - # Authenticate a client - # FIXME: "2" is the magic number for CLIENT_STATE_ESTABLISHED, - # for which currently no mapping exists. - self.air.setClientState(clientId, 2) - - # The client is now authenticated; create an Avatar - #self.maproot.sendUpdate("createAvatar", # Field to call - # [clientId]) # Arguments - self.maproot.create_avatar(clientId) - - # log login - self.notify.info("Login successful (user: %s)" % (username,)) - - else: - # Disconnect for bad auth - # FIXME: "122" is the magic number for login problems. - # See https://github.com/Astron/Astron/blob/master/doc/protocol/10-client.md - self.air.eject(clientId, 122, "Bad credentials") - - # log login attempt - self.notify.info("Ejecting client for bad credentials (user: %s)" % (username,)) + print("Received login request") + -# ------------------------------------------------------------------- -# DistributedMaproot -# * has all avatars in its zone 0 -# * generates new avatars -# ------------------------------------------------------------------- -#class DistributedMaproot(DistributedObject): -# def generateInit(self): -# print(datetime.now().strftime("%H:%M:%S")+" DistributedMaproot.generateInit() for "+str(self.doId)) - -#class DistributedMaprootOV(DistributedObjectOV): -# def generate(self): -# print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootOV.generate() for "+str(self.doId)) class DistributedMaproot(DistributedObject): pass class DistributedMaprootAI(DistributedObject): - def generate(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootAI.generate() for "+str(self.doId)) - - def set_maproot(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootAI.set_maproot() in "+str(self.doId)) - login_manager = self.air.generateGlobalObject(LoginManagerId, 'LoginManager') - login_manager.set_maproot(self.doId) - - def createAvatar(self, clientId): - print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootAI.createAvatar("+str(clientId)+") in "+str(self.doId)) - # Create the avatar - avatar = DistributedAvatarAI(self.air) - avatar.generateWithRequiredAndId(self.air.allocateChannel(), self.getDoId(), 0) # random doId, parentId, zoneId - self.air.setAI(avatar.doId, self.air.ourChannel) - # Set the client to be interested in our zone 0. He can't do - # that himself (or rather: shouldn't be allowed to) as he has - # no visibility of this object. - # We're always using the interest_id 0 because different - # clients use different ID spaces, so why make things more - # complicated? - self.air.clientAddInterest(clientId, 0, self.getDoId(), 0) # client, interest, parent, zone - # Set its owner to the client, upon which in the Clients repo - # magically OV (OwnerView) is generated. - self.air.setOwner(avatar.getDoId(), clientId) - # Declare this to be a session object. - self.air.clientAddSessionObject(clientId, self.getDoId()) + pass class DistributedMaprootUD(DistributedObject): - def generate(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootUD.generate() for "+str(self.doId)) - - def create_avatar(self, clientId): - print(datetime.now().strftime("%H:%M:%S")+" DistributedMaprootUD.create_avatar("+str(clientId)+") in "+str(self.doId)) - self.sendUpdate("createAvatar", # Field to call - [clientId]) # Arguments - -# ------------------------------------------------------------------- -# DistributedAvatar -# * represents players in the scene graph -# * routes indications of movement intents to AI -# * updates the actual position and orientation -# ------------------------------------------------------------------- + pass -class DistributedAvatar(DistributedObject): - def init(self): - print("DistributedAvatar") - - def generateInit(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatar.generateInit() for "+str(self.doId)) - model = base.loader.loadModel("models/smiley") - model.reparent_to(self) - model.setH(180.0) - # Signal app that this is its avatar - base.messenger.send("distributed_avatar", [self]) - - def delete(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatar.delete() for "+str(self.doId)) - - def setXYZH(self, *args): - DistributedNode.setXYZH(self, *args) -class DistributedAvatarOV(DistributedObject): - def init(self): - print("DistributedAvatarOV") - def generateInit(self): - # Make yourself known to the client - print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarOV.generate() for "+str(self.doId)) - base.messenger.send("avatar", [self]) - def delete(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarOV.delete() for "+str(self.doId)) - - def indicateIntent(self, heading, speed): - self.sendUpdate("indicateIntent", [heading, speed]) +class DistributedAvatar(DistributedObject): + pass class DistributedAvatarAI(DistributedObject): - def generate(self, repository=None): - print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarAI.generate() for "+str(self.doId)) - self.heading = 0.0 - self.speed = 0.0 - self.update_task = base.taskMgr.add(self.update_position, "Avatar position update") - - def delete(self): - print(datetime.now().strftime("%H:%M:%S")+" DistributedAvatarAI.delete() for "+str(self.doId)) - base.taskMgr.remove(self.update_task) - - def indicateIntent(self, heading, speed): - if (heading < -1.0) or (heading > 1.0) or (speed < -1.0) or (speed > 1.0): - # Client is cheating! - # FIXME: Eject client - return - self.heading = heading - self.speed = speed - - def update_position(self, task): - if (self.heading != 0.0) or (self.speed != 0.0): - dt = globalClock.getDt() - self.setH((self.getH() + self.heading * avatar_rotation_speed * dt) % 360.0) - self.setY(self, self.speed * avatar_speed * dt) - if self.getX() < -10.0: - self.setX(-10.0) - if self.getX() > 10.0: - self.setX(10.0) - if self.getY() < -10.0: - self.setY(-10.0) - if self.getY() > 10.0: - self.setY(10.0) - self.b_setXYZH(self.getX(), self.getY(), self.getZ(), self.getH()) - return Task.cont + pass + +class DistributedAvatarOV(DistributedObject): + pass From 5a7de8394f2bb6d2838ee32d5caa2eb44ccbde90 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sun, 26 Oct 2014 23:04:27 +0100 Subject: [PATCH 12/33] Sending correct CONTROL messages. --- astron/object_repository.py | 7 ++++--- example/transitional/example_services.py | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/astron/object_repository.py b/astron/object_repository.py index 86da728..5004d4f 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -112,6 +112,7 @@ def poll_forever(self): return def handle_datagram(self, dg): + print("ObjectRepository.handle_datagram(dg) was called, but should have been overloaded.") pass def create_view_from_datagram(self, dgi, cls_postfix = ''): @@ -150,7 +151,7 @@ def connect(self, connection_success, connection_failure, host=default_host, port=default_client_port): # FIXME: Handle connection failures ObjectRepository.connect(self, host, port) - self.send_CONTROL_ADD_CHANNEL() + self.send_CONTROL_ADD_CHANNEL(self.ai_channel) connection_success() def create_message_stub(self, sender, *recipients): @@ -175,13 +176,13 @@ def handle_datagram(self, dg): # Sending messages - def send_CONTROL_ADD_CHANNEL(self): + def send_CONTROL_ADD_CHANNEL(self, channel): # CONTROL messages don't have sender fields dg = Datagram() dg.add_uint8(1) # Number of recipients dg.add_uint64(1) # Recipient (control channel) dg.add_uint16(servermsg.CONTROL_ADD_CHANNEL) - dg.add_uint64(self.ai_channel) + dg.add_uint64(channel) self.send_datagram(dg) def send_STATESERVER_OBJECT_SET_AI(self, do_id): diff --git a/example/transitional/example_services.py b/example/transitional/example_services.py index dab1cc8..938b5d4 100755 --- a/example/transitional/example_services.py +++ b/example/transitional/example_services.py @@ -9,9 +9,9 @@ def connected(): print('Connection established.') - # FIXME: Does this object also need to be announced to astrond? login_manager = repo.create_view_by_classname('LoginManagerUD', 1234, 0, 0) - repo.send_STATESERVER_OBJECT_SET_AI(1234) + # repo.send_STATESERVER_OBJECT_SET_AI(1234) + repo.send_CONTROL_ADD_CHANNEL(1234) def failed(): print('Connection attempt failed.') From c3c50fb9ae690188ebc549386af8f53e37ec5443 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Mon, 27 Oct 2014 04:25:55 +0100 Subject: [PATCH 13/33] Tentative Implementation of receiving SET_FIELDs. --- astron/distributed_object.py | 81 +++++++++++++++++++++++++++++++++++- astron/object_repository.py | 8 ++++ 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 2247f29..9e7e679 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -11,6 +11,8 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): self.dclass = self.repo.mod.get_class(dclass_id) self.dmethod_name_to_id = dict([(self.dclass.get_field(dmethod_id).name(), dmethod_id) for dmethod_id in range(0, self.dclass.num_fields())]) + self.dmethod_id_to_name = dict([(dmethod_id, self.dclass.get_field(dmethod_id).name()) + for dmethod_id in range(0, self.dclass.num_fields())]) self.do_id = do_id self.parent = parent_id self.zone = zone_id @@ -28,8 +30,20 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): module.kTypeString: self.pack_string, module.kTypeVarstring: self.pack_string, } - # FIXME: Remove after debugging - #pprint(self.type_packer) + self.type_unpacker = {module.kTypeInt8: self.unpack_int8, + module.kTypeInt16: self.unpack_int16, + module.kTypeInt32: self.unpack_int32, + module.kTypeInt64: self.unpack_int64, + module.kTypeUint8: self.unpack_uint8, + module.kTypeUint16: self.unpack_uint16, + module.kTypeUint32: self.unpack_uint32, + module.kTypeUint64: self.unpack_uint64, + module.kTypeFloat32: self.unpack_float32, + module.kTypeFloat64: self.unpack_float64, + module.kTypeChar: self.unpack_char, + module.kTypeString: self.unpack_string, + module.kTypeVarstring: self.unpack_string, + } def init(self): print("DO created: %d (%s)" % (self.do_id, str(type(self)))) @@ -40,6 +54,21 @@ def delete(self): def call_dist_method(self, name, *args): pass + def update_field(self, field_id, dgi): + """Handles incoming SET_FIELD updates.""" + decoded_args = [] + field = self.dclass.get_field(field_id) + num_args = field.type().as_method().num_parameters() + for arg_id in range(0, num_args): + arg = field.type().as_method().get_parameter(arg_id) + arg_type = arg.type().subtype() + if arg_type == module.kTypeStruct: + decoded_args.append(self.unpack_struct(dgi, arg.type().as_struct())) + else: + decoded_args.append(self.type_unpacker[arg_type](dgi)) + print(decoded_args) + getattr(self, field.name())(*decoded_args) + def send_update(self, field_name, *values): dmethod_id = self.dmethod_name_to_id[field_name] field = self.dclass.get_field(dmethod_id) @@ -77,6 +106,18 @@ def pack_struct(self, dg, struct, *values): else: self.type_packer[arg_type](dg, values[arg_id]) + def unpack_struct(self, dgi, struct): + partial_args = [] + num_args = struct.num_fields() + for arg_id in range(0, num_args): + arg = struct.get_field(arg_id) + arg_type = arg.type().subtype() + if arg_type == module.kTypeStruct: + partial_args.append(self.unpack_struct(dgi, arg.type().as_struct())) + else: + partial_args.append(self.type_unpacker[arg_type](dgi)) + return partial_args + def pack_int8(self, dg, value): dg.add_int8(value) @@ -112,3 +153,39 @@ def pack_char(self, dg, value): def pack_string(self, dg, value): dg.add_string(value) + + def unpack_int8(self, dgi): + return dgi.read_int8() + + def unpack_int16(self, dgi): + return dgi.read_int16() + + def unpack_int32(self, dgi): + return dgi.read_int32() + + def unpack_int64(self, dgi): + return dgi.read_int64() + + def unpack_uint8(self, dgi): + return dgi.read_uint8() + + def unpack_uint16(self, dgi): + return dgi.read_uint16() + + def unpack_uint32(self, dgi): + return dgi.read_uint32() + + def unpack_uint64(self, dgi): + return dgi.read_uint64() + + def unpack_float32(self, dgi): + return dgi.read_float32() + + def unpack_float64(self, dgi): + return dgi.read_float64() + + def unpack_char(self, dgi): + return dgi.read_char() + + def unpack_string(self, dgi): + return dgi.read_string() diff --git a/astron/object_repository.py b/astron/object_repository.py index 5004d4f..7d8d470 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -144,6 +144,7 @@ def __init__(self, version_string, dcfilename=default_dcfilename, stateserver=40 self.ai_channel = ai_channel self.msg_type = MSG_TYPE_INTERNAL self.handlers.update({ + servermsg.STATESERVER_OBJECT_SET_FIELD: self.handle_STATESERVER_OBJECT_SET_FIELD, # FIXME: Add handlers for incoming messages }) @@ -191,6 +192,13 @@ def send_STATESERVER_OBJECT_SET_AI(self, do_id): dg.add_uint64(self.ai_channel) self.send_datagram(dg) + # Receive messages + + def handle_STATESERVER_OBJECT_SET_FIELD(self, dgi, sender, recipients): + do_id = dgi.read_uint32() + field_id = dgi.read_uint16() + self.distributed_objects[do_id].update_field(field_id, dgi) + class ClientRepository(ObjectRepository): def __init__(self, version_string, dcfilename=default_dcfilename): ObjectRepository.__init__(self, dcfilename=dcfilename) From 1eda75f3ef422bb45b1e83531e03dc4ea40e942d Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Fri, 31 Oct 2014 02:51:11 +0100 Subject: [PATCH 14/33] Callback management. Creating network objects. General shuffling around of things. Doesn't work properly yet, BTW. --- astron/distributed_object.py | 18 +++-- astron/object_repository.py | 91 +++++++++++++++++++++++- example/transitional/example_client.py | 2 +- example/transitional/example_services.py | 7 +- example/transitional/example_world.py | 21 +++--- example/transitional/simple_example.dc | 5 ++ example/transitional/simple_example.py | 39 +++++++--- 7 files changed, 155 insertions(+), 28 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 9e7e679..b764f31 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -1,7 +1,8 @@ from bamboo import module from bamboo.wire import Datagram from pprint import pprint -from astron.client_messages import CLIENT_OBJECT_SET_FIELD +import client_messages as clientmsg +import internal_messages as servermsg from astron.object_repository import MSG_TYPE_CLIENT, MSG_TYPE_INTERNAL class DistributedObject: @@ -53,7 +54,11 @@ def delete(self): def call_dist_method(self, name, *args): pass - + + def acquire_ai(self): + # FIXME: This should have more intelligence, i.e. using GET_AI (CHANGE_AI?) + self.repo.send_STATESERVER_OBJECT_SET_AI(self.do_id) + def update_field(self, field_id, dgi): """Handles incoming SET_FIELD updates.""" decoded_args = [] @@ -78,10 +83,11 @@ def send_update(self, field_name, *values): else: if self.repo.msg_type == MSG_TYPE_CLIENT: dg = self.repo.create_message_stub() + dg.add_int16(clientmsg.CLIENT_OBJECT_SET_FIELD) else: # FIXME: If this an AIR object, recipients and sender have to be provided here. - dg = self.repo.create_message_stub() - dg.add_int16(CLIENT_OBJECT_SET_FIELD) + dg = self.repo.create_message_stub(self.do_id, self.do_id) + dg.add_int16(servermsg.STATESERVER_OBJECT_SET_FIELD) dg.add_int32(self.do_id) dg.add_int16(dmethod_id) for arg_id in range(0, num_args): @@ -189,3 +195,7 @@ def unpack_char(self, dgi): def unpack_string(self, dgi): return dgi.read_string() + + # Sending + + diff --git a/astron/object_repository.py b/astron/object_repository.py index 7d8d470..bfd95ce 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -49,9 +49,51 @@ def __init__(self, dcfilename=default_dcfilename): self.handlers = {} # FIXME: Maybe move this into ClientRepository, if Internals won't get Interests in the future. + # FIXME: Actually, fold this into the general callback mechanism. self.interest_counters = {} self.interest_callback_map = {} + # The callback system for handling *_RESP messages + self.msg_to_msgresp_map = { + servermsg.STATESERVER_OBJECT_GET_FIELD : servermsg.STATESERVER_OBJECT_GET_FIELD_RESP, + servermsg.STATESERVER_OBJECT_GET_FIELDS : servermsg.STATESERVER_OBJECT_GET_FIELDS_RESP, + servermsg.STATESERVER_OBJECT_GET_ALL : servermsg.STATESERVER_OBJECT_GET_ALL_RESP, + servermsg.STATESERVER_OBJECT_GET_LOCATION : servermsg.STATESERVER_OBJECT_GET_LOCATION_RESP, + servermsg.STATESERVER_OBJECT_GET_AI : servermsg.STATESERVER_OBJECT_GET_AI_RESP, + servermsg.STATESERVER_OBJECT_GET_OWNER : servermsg.STATESERVER_OBJECT_GET_OWNER_RESP, + servermsg.STATESERVER_OBJECT_GET_ZONE_COUNT : servermsg.STATESERVER_OBJECT_GET_ZONE_COUNT_RESP, + servermsg.STATESERVER_OBJECT_GET_ZONES_COUNT : servermsg.STATESERVER_OBJECT_GET_ZONES_COUNT_RESP, + servermsg.STATESERVER_OBJECT_GET_CHILD_COUNT : servermsg.STATESERVER_OBJECT_GET_CHILD_COUNT_RESP, + servermsg.DBSS_OBJECT_GET_ACTIVATED : servermsg.DBSS_OBJECT_GET_ACTIVATED_RESP, + servermsg.DBSERVER_CREATE_OBJECT : servermsg.DBSERVER_CREATE_OBJECT_RESP, + servermsg.DBSERVER_OBJECT_GET_FIELD : servermsg.DBSERVER_OBJECT_GET_FIELD_RESP, + servermsg.DBSERVER_OBJECT_GET_FIELDS : servermsg.DBSERVER_OBJECT_GET_FIELDS_RESP, + servermsg.DBSERVER_OBJECT_GET_ALL : servermsg.DBSERVER_OBJECT_GET_ALL_RESP, + servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EQUALS : servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EQUALS_RESP, + servermsg.DBSERVER_OBJECT_SET_FIELDS_IF_EQUALS: servermsg.DBSERVER_OBJECT_SET_FIELDS_IF_EQUALS_RESP, + servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EMPTY : servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EMPTY_RESP, + } + self.context_counters = { + servermsg.STATESERVER_OBJECT_GET_FIELD_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_FIELDS_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_ALL_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_LOCATION_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_AI_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_OWNER_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_ZONE_COUNT_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_ZONES_COUNT_RESP : 0, + servermsg.STATESERVER_OBJECT_GET_CHILD_COUNT_RESP : 0, + servermsg.DBSS_OBJECT_GET_ACTIVATED_RESP : 0, + servermsg.DBSERVER_CREATE_OBJECT_RESP : 0, + servermsg.DBSERVER_OBJECT_GET_FIELD_RESP : 0, + servermsg.DBSERVER_OBJECT_GET_FIELDS_RESP : 0, + servermsg.DBSERVER_OBJECT_GET_ALL_RESP : 0, + servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EQUALS_RESP : 0, + servermsg.DBSERVER_OBJECT_SET_FIELDS_IF_EQUALS_RESP: 0, + servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EMPTY_RESP : 0, + } + self.callbacks = {} + def create_dclass_dicts(self): self.dclass_id_to_cls = {} # (, 'PF'): self.dclass_id_to_name = {} # (, 'PF'): 'DClass' @@ -115,6 +157,8 @@ def handle_datagram(self, dg): print("ObjectRepository.handle_datagram(dg) was called, but should have been overloaded.") pass + # Creating client/AI-side views + def create_view_from_datagram(self, dgi, cls_postfix = ''): do_id = dgi.read_uint32() parent_id = dgi.read_uint32() @@ -127,15 +171,27 @@ def create_view_from_datagram(self, dgi, cls_postfix = ''): # FIXME: Read the field values from the dgi and apply them dist_obj.init() - def create_view_by_classname(self, cls_name, do_id, parent_id, zone_id): + def create_distobjglobal_view(self, cls_name, do_id, parent_id, zone_id): cls = self.dclass_name_to_cls[cls_name] dclass_id = self.dclass_name_to_id[cls_name] dist_obj = cls(self, dclass_id, do_id, parent_id, zone_id) self.distributed_objects[do_id] = dist_obj - # FIXME: Read the field values from the dgi and apply them dist_obj.init() return dist_obj + # Callback management for *_RESP messages + + def register_callback(self, msg_type, callback, args = [], kwargs = {}): + resp_msg_type = self.msg_to_msgresp_map[msg_type] + context = self.context_counters[resp_msg_type] + self.context_counters[resp_msg_type] += 1 + self.callbacks[(resp_msg_type, context)] = (callback, args, kwargs) + return context + + def fire_callback(self, resp_msg_type, context): + callback = self.callbacks[(resp_msg_type, context)] + del self.callbacks[(resp_msg_type, context)] + return callback class InternalRepository(ObjectRepository): def __init__(self, version_string, dcfilename=default_dcfilename, stateserver=400000, ai_channel=500000): @@ -175,6 +231,10 @@ def handle_datagram(self, dg): else: print("Received unhandled message type " + str(msgtype)) + def create_distobj(self, cls_name, do_id, parent_id, zone_id): + dclass_id = self.dclass_name_to_id[cls_name] + self.send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(dclass_id, do_id, parent_id, zone_id) + # Sending messages def send_CONTROL_ADD_CHANNEL(self, channel): @@ -191,6 +251,33 @@ def send_STATESERVER_OBJECT_SET_AI(self, do_id): dg.add_uint16(servermsg.STATESERVER_OBJECT_SET_AI) dg.add_uint64(self.ai_channel) self.send_datagram(dg) + + def send_STATESERVER_DELETE_AI_OBJECTS(self): + dg = self.create_message_stub(self.ai_channel, self.stateserver) + dg.add_uint16(servermsg.STATESERVER_DELETE_AI_OBJECTS) + dg.add_uint64(self.ai_channel) + self.send_datagram(dg) + + def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(self, dclass_id, do_id, parent, zone): + dg = self.create_message_stub(self.ai_channel, self.stateserver) + dg.add_uint16(servermsg.STATESERVER_DELETE_AI_OBJECTS) + dg.add_uint32(do_id) + dg.add_uint32(parent) + dg.add_uint32(zone) + dg.add_uint16(dclass_id) + # FIXME: Add REQUIRED fields + self.send_datagram(dg) + + def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER(self): + dg = self.repo.create_message_stub(self.do_id, self.stateserver) + dg.add_uint16(servermsg.STATESERVER_DELETE_AI_OBJECTS) + dg.add_uint32(self.do_id) + dg.add_uint32(self.parent) + dg.add_uint32(self.zone) + dg.add_uint16(self.dclass_id) + # FIXME: Add REQUIRED fields + # FIXME: Add OTHER fields + self.send_datagram(dg) # Receive messages diff --git a/example/transitional/example_client.py b/example/transitional/example_client.py index 6753266..82b687f 100755 --- a/example/transitional/example_client.py +++ b/example/transitional/example_client.py @@ -9,7 +9,7 @@ def connected(): print('Connection established.') - login_manager = repo.create_view_by_classname('LoginManager', 1234, 0, 0) + login_manager = repo.create_distobjglobal_view('LoginManager', 1234, 0, 0) login_manager.login("guest", "guest") def ejected(error_code, reason): diff --git a/example/transitional/example_services.py b/example/transitional/example_services.py index 938b5d4..a0874f6 100755 --- a/example/transitional/example_services.py +++ b/example/transitional/example_services.py @@ -9,8 +9,7 @@ def connected(): print('Connection established.') - login_manager = repo.create_view_by_classname('LoginManagerUD', 1234, 0, 0) - # repo.send_STATESERVER_OBJECT_SET_AI(1234) + login_manager = repo.create_distobjglobal_view('LoginManagerUD', 1234, 0, 0) repo.send_CONTROL_ADD_CHANNEL(1234) def failed(): @@ -19,6 +18,6 @@ def failed(): repo.connect(connected, failed, host = '127.0.0.1', port = 7199) while True: + print("Polling...") repo.poll_till_empty() - #print(repo.poll_datagram()) - sleep(0.1) + sleep(2) diff --git a/example/transitional/example_world.py b/example/transitional/example_world.py index 258eff4..300ef56 100755 --- a/example/transitional/example_world.py +++ b/example/transitional/example_world.py @@ -5,22 +5,25 @@ from astron.object_repository import InternalRepository if __name__ == '__main__': - repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc') + repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500001) def connected(): print('Connection established.') - # FIXME: Create maproot object and view only instead - login_manager = repo.create_view_by_classname('LoginManagerAI', 1234, 0, 0) - - def ejected(error_code, reason): - print('Got ejected (%i): %s' % (error_code, reason)) + repo.send_CONTROL_ADD_CHANNEL(1000) + repo.send_CONTROL_ADD_CHANNEL(10000) + repo.send_CONTROL_ADD_CHANNEL(1000 * 2**32 | 0) + repo.send_CONTROL_ADD_CHANNEL(10000 * 2**32 | 0) + repo.send_STATESERVER_OBJECT_SET_AI(10000) + repo.create_distobj('GameRootAI', 1000, 0, 0) + repo.create_distobj('DistributedMaproot', 10000, 1000, 0) + # maproot.enter() def failed(): print('Connection attempt failed.') - repo.connect(connected, failed, ejected, host = '127.0.0.1', port = 7199) + repo.connect(connected, failed, host = '127.0.0.1', port = 7199) while True: + print("Polling...") repo.poll_till_empty() - #print(repo.poll_datagram()) - sleep(0.1) + sleep(2) diff --git a/example/transitional/simple_example.dc b/example/transitional/simple_example.dc index 6dff332..2409b68 100644 --- a/example/transitional/simple_example.dc +++ b/example/transitional/simple_example.dc @@ -4,10 +4,15 @@ typedef uint32 zoneId; typedef uint64 channel; // The Python Views for these distributed classes. +from simple_example import GameRoot/AI from simple_example import LoginManager/AI/UD from simple_example import DistributedMaproot/AI/UD from simple_example import DistributedAvatar/AI/OV +// A "dead" object (that processes nothing). AIs can put the roots +// of the visibility subtrees that they control into its zones. +dclass GameRoot {}; + // A simple DOG for username/password authentication and handoff to // the DistributedMaproot for avatar creation. dclass LoginManager { diff --git a/example/transitional/simple_example.py b/example/transitional/simple_example.py index b140c66..857243e 100644 --- a/example/transitional/simple_example.py +++ b/example/transitional/simple_example.py @@ -9,6 +9,13 @@ avatar_speed = 3.0 avatar_rotation_speed = 90.0 + +class GameRoot(DistributedObject): + pass + +class GameRootAI(DistributedObject): + pass + # ------------------------------------------------------------------- # LoginManager # * Registers a DistributedMaproot @@ -28,31 +35,47 @@ class LoginManagerAI(DistributedObject): def init(self): print("LoginManagerAI view created") - #def set_maproot(self, maproot_doId): - # print("LoginManagerAI view sends set_maproot") - # self.sendUpdate("set_maproot", [maproot_doId]) + def set_maproot(self, maproot_doId): + print("LoginManagerAI view sends set_maproot") + self.send_update("set_maproot", maproot_doId) class LoginManagerUD(DistributedObject): def init(self): print("LoginManagerUD view created") + def set_maproot(self, maproot_doId): + self.maproot_do_id = maproot_doId + print("Maproot DO ID = %d" % (maproot_doId, )) + def login(self, username, password): print("Received login request") - - +# ------------------------------------------------------------------- +# DistributedMaproot +# * has all avatars in its zone 0 +# * generates new avatars +# ------------------------------------------------------------------- class DistributedMaproot(DistributedObject): pass class DistributedMaprootAI(DistributedObject): - pass + def init(self): + print("DistributedMaprootAI view created") + # FIXME: ENTER astrond DO + # Register with LoginManager + self.login_manager = self.repo.create_distobj('LoginManagerAI', 1234, 0, 0) + self.login_manager.set_maproot(self.do_id) class DistributedMaprootUD(DistributedObject): pass - - +# ------------------------------------------------------------------- +# DistributedAvatar +# * represents players in the scene graph +# * routes indications of movement intents to AI +# * updates the actual position and orientation +# ------------------------------------------------------------------- class DistributedAvatar(DistributedObject): pass From eccd4a85571193335498b8afb333ccba2eb04cc0 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sun, 2 Nov 2014 04:48:45 +0100 Subject: [PATCH 15/33] Added file for variables shared between processes. --- example/transitional/shared_constants.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 example/transitional/shared_constants.py diff --git a/example/transitional/shared_constants.py b/example/transitional/shared_constants.py new file mode 100644 index 0000000..1c329a0 --- /dev/null +++ b/example/transitional/shared_constants.py @@ -0,0 +1,6 @@ +LOGIN_MANAGER_DO_ID = 1234 + +MAP_ROOT_DO_ID = 10000 +MAP_ROOT_PARENT = LOGIN_MANAGER_DO_ID +MAP_ROOT_ZONE = 0 +MAP_ROOT_LOCATION = MAP_ROOT_PARENT * 2**32 | MAP_ROOT_ZONE \ No newline at end of file From 139b04c4366a9a031e3530dab65504d36d57baec Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sun, 2 Nov 2014 04:52:58 +0100 Subject: [PATCH 16/33] Removed GameRoot distobj. Small clean-ups. Stubs for more messages. Bugfixes. --- astron/distributed_object.py | 4 +- astron/object_repository.py | 49 ++++++++++++++++++++---- example/transitional/example_client.py | 3 +- example/transitional/example_services.py | 10 +++-- example/transitional/example_world.py | 14 ++----- example/transitional/simple_example.dc | 5 --- example/transitional/simple_example.py | 28 ++++++++------ 7 files changed, 71 insertions(+), 42 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index b764f31..ca3048a 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -47,7 +47,7 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): } def init(self): - print("DO created: %d (%s)" % (self.do_id, str(type(self)))) + print("DO created without custom init(): %d (%s)" % (self.do_id, str(type(self)))) def delete(self): print("DO deleted: %d" % (self.do_id, )) @@ -71,7 +71,7 @@ def update_field(self, field_id, dgi): decoded_args.append(self.unpack_struct(dgi, arg.type().as_struct())) else: decoded_args.append(self.type_unpacker[arg_type](dgi)) - print(decoded_args) + # print("Updating field %s in %d with args %s" % (field.name(), self.do_id, str(decoded_args))) getattr(self, field.name())(*decoded_args) def send_update(self, field_name, *values): diff --git a/astron/object_repository.py b/astron/object_repository.py index bfd95ce..76508e2 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -171,10 +171,10 @@ def create_view_from_datagram(self, dgi, cls_postfix = ''): # FIXME: Read the field values from the dgi and apply them dist_obj.init() - def create_distobjglobal_view(self, cls_name, do_id, parent_id, zone_id): + def create_distobjglobal_view(self, cls_name, do_id): cls = self.dclass_name_to_cls[cls_name] dclass_id = self.dclass_name_to_id[cls_name] - dist_obj = cls(self, dclass_id, do_id, parent_id, zone_id) + dist_obj = cls(self, dclass_id, do_id, 0, 0) self.distributed_objects[do_id] = dist_obj dist_obj.init() return dist_obj @@ -200,9 +200,28 @@ def __init__(self, version_string, dcfilename=default_dcfilename, stateserver=40 self.ai_channel = ai_channel self.msg_type = MSG_TYPE_INTERNAL self.handlers.update({ - servermsg.STATESERVER_OBJECT_SET_FIELD: self.handle_STATESERVER_OBJECT_SET_FIELD, + servermsg.STATESERVER_OBJECT_SET_FIELD: self.handle_STATESERVER_OBJECT_SET_FIELD, + servermsg.STATESERVER_OBJECT_CHANGING_LOCATION: self.handle_STATESERVER_OBJECT_CHANGING_LOCATION, + servermsg.STATESERVER_OBJECT_GET_AI: self.handle_STATESERVER_OBJECT_GET_AI, + servermsg.STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED: self.handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED, + servermsg.STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED: self.handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED, # FIXME: Add handlers for incoming messages - }) + }) + self.global_views = {} + self.repo_interests = set() + + def add_ai_interest(self, distobj_id, zone_id): + self.repo_interests.add(distobj_id * 2**32 | zone_id) + # FIXME: As do_ids and zones may be of different sizes, + # this calculation has to take that into account. + self.send_CONTROL_ADD_CHANNEL(distobj_id * 2**32 | zone_id) + # FIXME: Request list of objects already existing in that + # zone for ENTER. + # FIXME: Messages for DOs that haven't entered yet may come + # over the control channel. Either some kind of solution is + # needed, or AIR interests shall be implemented in Astron as + # actual messages. + # FIXME: There should also be remove_ai_interest(distobj, zone) def connect(self, connection_success, connection_failure, host=default_host, port=default_client_port): @@ -225,15 +244,17 @@ def handle_datagram(self, dg): recipients = [dgi.read_uint64() for _ in range(0, num_recipients)] sender = dgi.read_uint64() msgtype = dgi.read_uint16() - print("Handling %d" % (msgtype, )) if msgtype in self.handlers.keys(): self.handlers[msgtype](dgi, sender, recipients) else: print("Received unhandled message type " + str(msgtype)) - def create_distobj(self, cls_name, do_id, parent_id, zone_id): + def create_distobj(self, cls_name, do_id, parent_id, zone_id, set_ai = False): dclass_id = self.dclass_name_to_id[cls_name] self.send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(dclass_id, do_id, parent_id, zone_id) + if set_ai: + self.send_STATESERVER_OBJECT_SET_AI(do_id) + # Sending messages @@ -260,7 +281,7 @@ def send_STATESERVER_DELETE_AI_OBJECTS(self): def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(self, dclass_id, do_id, parent, zone): dg = self.create_message_stub(self.ai_channel, self.stateserver) - dg.add_uint16(servermsg.STATESERVER_DELETE_AI_OBJECTS) + dg.add_uint16(servermsg.STATESERVER_CREATE_OBJECT_WITH_REQUIRED) dg.add_uint32(do_id) dg.add_uint32(parent) dg.add_uint32(zone) @@ -270,7 +291,7 @@ def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(self, dclass_id, do_id, parent, def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER(self): dg = self.repo.create_message_stub(self.do_id, self.stateserver) - dg.add_uint16(servermsg.STATESERVER_DELETE_AI_OBJECTS) + dg.add_uint16(servermsg.STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER) dg.add_uint32(self.do_id) dg.add_uint32(self.parent) dg.add_uint32(self.zone) @@ -285,7 +306,19 @@ def handle_STATESERVER_OBJECT_SET_FIELD(self, dgi, sender, recipients): do_id = dgi.read_uint32() field_id = dgi.read_uint16() self.distributed_objects[do_id].update_field(field_id, dgi) + + def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, dgi, sender, recipients): + print("handle_STATESERVER_OBJECT_CHANGING_LOCATION", sender, recipients) + + def handle_STATESERVER_OBJECT_GET_AI(self, dgi, sender, recipients): + print("handle_STATESERVER_OBJECT_GET_AI", sender, recipients) + def handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED(self, dgi, sender, recipients): + print("handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED", sender, recipients) + + def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, sender, recipients): + self.create_view_from_datagram(dgi, cls_postfix = 'AI') + class ClientRepository(ObjectRepository): def __init__(self, version_string, dcfilename=default_dcfilename): ObjectRepository.__init__(self, dcfilename=dcfilename) diff --git a/example/transitional/example_client.py b/example/transitional/example_client.py index 82b687f..1bb25ae 100755 --- a/example/transitional/example_client.py +++ b/example/transitional/example_client.py @@ -3,13 +3,14 @@ from time import sleep from astron.object_repository import ClientRepository +from shared_constants import * if __name__ == '__main__': repo = ClientRepository('SimpleExample v0.2', 'simple_example.dc') def connected(): print('Connection established.') - login_manager = repo.create_distobjglobal_view('LoginManager', 1234, 0, 0) + login_manager = repo.create_distobjglobal_view('LoginManager', LOGIN_MANAGER_DO_ID) login_manager.login("guest", "guest") def ejected(error_code, reason): diff --git a/example/transitional/example_services.py b/example/transitional/example_services.py index a0874f6..d41e6fd 100755 --- a/example/transitional/example_services.py +++ b/example/transitional/example_services.py @@ -3,14 +3,17 @@ from time import sleep from astron.object_repository import InternalRepository +from shared_constants import * if __name__ == '__main__': repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500000) def connected(): print('Connection established.') - login_manager = repo.create_distobjglobal_view('LoginManagerUD', 1234, 0, 0) - repo.send_CONTROL_ADD_CHANNEL(1234) + login_manager = repo.create_distobjglobal_view('LoginManagerUD', LOGIN_MANAGER_DO_ID) + # FIXME: This should be folded into a 'set_ai = True' kwarg into create_distobjglobal_view + repo.send_CONTROL_ADD_CHANNEL(LOGIN_MANAGER_DO_ID) + repo.add_ai_interest(MAP_ROOT_PARENT, MAP_ROOT_ZONE) def failed(): print('Connection attempt failed.') @@ -18,6 +21,5 @@ def failed(): repo.connect(connected, failed, host = '127.0.0.1', port = 7199) while True: - print("Polling...") repo.poll_till_empty() - sleep(2) + sleep(0.1) diff --git a/example/transitional/example_world.py b/example/transitional/example_world.py index 300ef56..24c68e9 100755 --- a/example/transitional/example_world.py +++ b/example/transitional/example_world.py @@ -3,20 +3,14 @@ from time import sleep from astron.object_repository import InternalRepository +from shared_constants import * if __name__ == '__main__': repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500001) def connected(): print('Connection established.') - repo.send_CONTROL_ADD_CHANNEL(1000) - repo.send_CONTROL_ADD_CHANNEL(10000) - repo.send_CONTROL_ADD_CHANNEL(1000 * 2**32 | 0) - repo.send_CONTROL_ADD_CHANNEL(10000 * 2**32 | 0) - repo.send_STATESERVER_OBJECT_SET_AI(10000) - repo.create_distobj('GameRootAI', 1000, 0, 0) - repo.create_distobj('DistributedMaproot', 10000, 1000, 0) - # maproot.enter() + repo.create_distobj('DistributedMaproot', MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, set_ai = True) def failed(): print('Connection attempt failed.') @@ -24,6 +18,6 @@ def failed(): repo.connect(connected, failed, host = '127.0.0.1', port = 7199) while True: - print("Polling...") + # print("Polling...") repo.poll_till_empty() - sleep(2) + sleep(0.1) diff --git a/example/transitional/simple_example.dc b/example/transitional/simple_example.dc index 2409b68..6dff332 100644 --- a/example/transitional/simple_example.dc +++ b/example/transitional/simple_example.dc @@ -4,15 +4,10 @@ typedef uint32 zoneId; typedef uint64 channel; // The Python Views for these distributed classes. -from simple_example import GameRoot/AI from simple_example import LoginManager/AI/UD from simple_example import DistributedMaproot/AI/UD from simple_example import DistributedAvatar/AI/OV -// A "dead" object (that processes nothing). AIs can put the roots -// of the visibility subtrees that they control into its zones. -dclass GameRoot {}; - // A simple DOG for username/password authentication and handoff to // the DistributedMaproot for avatar creation. dclass LoginManager { diff --git a/example/transitional/simple_example.py b/example/transitional/simple_example.py index 857243e..b8ed0e5 100644 --- a/example/transitional/simple_example.py +++ b/example/transitional/simple_example.py @@ -1,21 +1,13 @@ -from astron.object_repository import DistributedObject - from datetime import datetime -# Constant DO and channel IDs -LoginManagerId = 1234 +from astron.object_repository import DistributedObject +from shared_constants import * # Game settings avatar_speed = 3.0 avatar_rotation_speed = 90.0 -class GameRoot(DistributedObject): - pass - -class GameRootAI(DistributedObject): - pass - # ------------------------------------------------------------------- # LoginManager # * Registers a DistributedMaproot @@ -41,6 +33,7 @@ def set_maproot(self, maproot_doId): class LoginManagerUD(DistributedObject): def init(self): + self.maproot_do_id = None print("LoginManagerUD view created") def set_maproot(self, maproot_doId): @@ -49,6 +42,17 @@ def set_maproot(self, maproot_doId): def login(self, username, password): print("Received login request") + if self.maproot_do_id != None: + if username == "guest" and password == "guest": + print("Logging in successfully") + else: # Bad credentials + # FIXME: Implement + print("Disconnecting for bad credentials") + else: + # maproot hasn't contacted us yet. + # FIXME: ...or has left, and no replacement has arrived. + # FIXME: Implement a disconnection with reason "game not up yet". + print("Dropping connection attempt due to missing maproot") # ------------------------------------------------------------------- # DistributedMaproot @@ -64,8 +68,8 @@ def init(self): print("DistributedMaprootAI view created") # FIXME: ENTER astrond DO # Register with LoginManager - self.login_manager = self.repo.create_distobj('LoginManagerAI', 1234, 0, 0) - self.login_manager.set_maproot(self.do_id) + self.login_manager = self.repo.create_distobjglobal_view('LoginManagerAI', LOGIN_MANAGER_DO_ID) + # self.login_manager.set_maproot(self.do_id) class DistributedMaprootUD(DistributedObject): pass From de712da79f244d40b3b276c04858bcb6110976f1 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Mon, 3 Nov 2014 17:46:16 +0100 Subject: [PATCH 17/33] STATESERVER_OBJECT_CHANGING_LOCATION now reaches recipient distobj. LoginManager uses "Interest" do manage several maproots. Assorted small changes. --- astron/distributed_object.py | 14 +++--- astron/object_repository.py | 41 +++++++++++---- example/transitional/example_services.py | 2 +- example/transitional/example_world.py | 2 +- example/transitional/simple_example.dc | 5 +- example/transitional/simple_example.py | 64 ++++++++++++++++-------- 6 files changed, 88 insertions(+), 40 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index ca3048a..1433110 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -52,14 +52,11 @@ def init(self): def delete(self): print("DO deleted: %d" % (self.do_id, )) - def call_dist_method(self, name, *args): - pass - def acquire_ai(self): # FIXME: This should have more intelligence, i.e. using GET_AI (CHANGE_AI?) self.repo.send_STATESERVER_OBJECT_SET_AI(self.do_id) - def update_field(self, field_id, dgi): + def update_field(self, sender, field_id, dgi): """Handles incoming SET_FIELD updates.""" decoded_args = [] field = self.dclass.get_field(field_id) @@ -72,10 +69,12 @@ def update_field(self, field_id, dgi): else: decoded_args.append(self.type_unpacker[arg_type](dgi)) # print("Updating field %s in %d with args %s" % (field.name(), self.do_id, str(decoded_args))) - getattr(self, field.name())(*decoded_args) + getattr(self, field.name())(sender, *decoded_args) def send_update(self, field_name, *values): + """Handles outgoing SET_FIELD updates.""" dmethod_id = self.dmethod_name_to_id[field_name] + # print(" send_update to field %s, dmethod_id %d" % (field_name, dmethod_id)) field = self.dclass.get_field(dmethod_id) num_args = field.type().as_method().num_parameters() if num_args != len(values): @@ -198,4 +197,7 @@ def unpack_string(self, dgi): # Sending - + # Handle + def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): + """Override this to react to STATESERVER_OBJECT_CHANGING_LOCATION messages.""" + pass diff --git a/astron/object_repository.py b/astron/object_repository.py index 76508e2..0be5f4c 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -29,6 +29,16 @@ default_client_port = 7198 default_dcfilename = "astron.dc" +# FIXME: This needs to be moved into a shared name space. +# FIXME: This needs to acknowledge the fact that there may be 128 bit +# locations (64 bit do_ids and zones). +def parent_zone_to_location(parent, zone): + return parent * 2**32 | zone + +def location_to_parent_zone(location): + return (location / 2**32, location % 2**32) + + class ObjectRepository(Connection): def __init__(self, dcfilename=default_dcfilename): @@ -40,9 +50,6 @@ def __init__(self, dcfilename=default_dcfilename): dcfile.parse_dcfile(self.mod, dcfilename) # Create class definition dicts self.create_dclass_dicts() - # FIXME: Remove this after debugging - #pprint(self.dclass_id_to_cls) - #pprint(self.dclass_name_to_cls) self.distributed_objects = {} self.owner_views = {} @@ -118,6 +125,10 @@ def create_dclass_dicts(self): self.dclass_name_to_cls[base_class + postfix] = cls self.dclass_name_to_cls[(base_class, postfix)] = cls + def distobj_by_do_id(self, do_id): + # FIXME: try/except this + return self.distributed_objects[do_id] + def poll_till_empty(self): """Process all received messages. @@ -211,10 +222,10 @@ def __init__(self, version_string, dcfilename=default_dcfilename, stateserver=40 self.repo_interests = set() def add_ai_interest(self, distobj_id, zone_id): - self.repo_interests.add(distobj_id * 2**32 | zone_id) + self.repo_interests.add(parent_zone_to_location(distobj_id, zone_id)) # FIXME: As do_ids and zones may be of different sizes, # this calculation has to take that into account. - self.send_CONTROL_ADD_CHANNEL(distobj_id * 2**32 | zone_id) + self.send_CONTROL_ADD_CHANNEL(parent_zone_to_location(distobj_id, zone_id)) # FIXME: Request list of objects already existing in that # zone for ENTER. # FIXME: Messages for DOs that haven't entered yet may come @@ -305,18 +316,32 @@ def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER(self): def handle_STATESERVER_OBJECT_SET_FIELD(self, dgi, sender, recipients): do_id = dgi.read_uint32() field_id = dgi.read_uint16() - self.distributed_objects[do_id].update_field(field_id, dgi) + self.distributed_objects[do_id].update_field(sender, field_id, dgi) def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, dgi, sender, recipients): print("handle_STATESERVER_OBJECT_CHANGING_LOCATION", sender, recipients) + do_id = dgi.read_uint32() + new_parent = dgi.read_uint32() + new_zone = dgi.read_uint32() + old_parent = dgi.read_uint32() + old_zone = dgi.read_uint32() + # print(" %d moves from (%d, %d) to (%d, %d)" % (do_id, old_parent, old_zone, new_parent, new_zone)) + # FIXME: Now what to do with that information? + for recipient in recipients: + if recipient in self.distributed_objects.keys(): + self.distributed_objects[recipient].handle_STATESERVER_OBJECT_CHANGING_LOCATION(sender, do_id, new_parent, new_zone, old_parent, old_zone) def handle_STATESERVER_OBJECT_GET_AI(self, dgi, sender, recipients): print("handle_STATESERVER_OBJECT_GET_AI", sender, recipients) + context = dgi.read_uint32() + print(" Context: %d" % (context, )) + # FIXME: Implement def handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED(self, dgi, sender, recipients): - print("handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED", sender, recipients) + self.create_view_from_datagram(dgi, cls_postfix = 'AE') def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, sender, recipients): + print("handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED", sender, recipients) self.create_view_from_datagram(dgi, cls_postfix = 'AI') class ClientRepository(ObjectRepository): @@ -381,8 +406,6 @@ def send_CLIENT_ADD_INTEREST(self, parent_id, zone_id, interest_id = 0, callback = False, callback_args = [], callback_kwargs = {}): - # FIXME: interest_id (uint16), parent_id (uint32), zone_id (uint32) should - # be asserted. if not (interest_id in self.interest_counters.keys()): self.interest_counters[interest_id] = -1 # FIXME: This needs to be protected against uint32 roll-overs. I'll probably diff --git a/example/transitional/example_services.py b/example/transitional/example_services.py index d41e6fd..01a39ee 100755 --- a/example/transitional/example_services.py +++ b/example/transitional/example_services.py @@ -3,7 +3,7 @@ from time import sleep from astron.object_repository import InternalRepository -from shared_constants import * +from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE if __name__ == '__main__': repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500000) diff --git a/example/transitional/example_world.py b/example/transitional/example_world.py index 24c68e9..64489e1 100755 --- a/example/transitional/example_world.py +++ b/example/transitional/example_world.py @@ -3,7 +3,7 @@ from time import sleep from astron.object_repository import InternalRepository -from shared_constants import * +from shared_constants import MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE if __name__ == '__main__': repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500001) diff --git a/example/transitional/simple_example.dc b/example/transitional/simple_example.dc index 6dff332..bfdb7e8 100644 --- a/example/transitional/simple_example.dc +++ b/example/transitional/simple_example.dc @@ -5,19 +5,18 @@ typedef uint64 channel; // The Python Views for these distributed classes. from simple_example import LoginManager/AI/UD -from simple_example import DistributedMaproot/AI/UD +from simple_example import DistributedMaproot/AI/UD/AE from simple_example import DistributedAvatar/AI/OV // A simple DOG for username/password authentication and handoff to // the DistributedMaproot for avatar creation. dclass LoginManager { - set_maproot(doId maproot); login(string username, string password) clsend; }; // The root object of the map, container for the DistributedAvatars. dclass DistributedMaproot { - createAvatar(channel client) airecv; + create_avatar(channel client) airecv; }; // The actual class for avatar control. diff --git a/example/transitional/simple_example.py b/example/transitional/simple_example.py index b8ed0e5..2addfbd 100644 --- a/example/transitional/simple_example.py +++ b/example/transitional/simple_example.py @@ -1,7 +1,10 @@ from datetime import datetime from astron.object_repository import DistributedObject -from shared_constants import * +from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_ZONE +import random + +from pprint import pprint # Game settings avatar_speed = 3.0 @@ -17,7 +20,7 @@ class LoginManager(DistributedObject): def init(self): - print("LoginManager view created") + print("LoginManager view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) def login(self, username, password): print("Client logging in") @@ -25,35 +28,44 @@ def login(self, username, password): class LoginManagerAI(DistributedObject): def init(self): - print("LoginManagerAI view created") + print("LoginManagerAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - def set_maproot(self, maproot_doId): - print("LoginManagerAI view sends set_maproot") - self.send_update("set_maproot", maproot_doId) + #def set_maproot(self, maproot_doId): + # print("LoginManagerAI view sends set_maproot") + # self.send_update("set_maproot", maproot_doId) class LoginManagerUD(DistributedObject): def init(self): - self.maproot_do_id = None - print("LoginManagerUD view created") - - def set_maproot(self, maproot_doId): - self.maproot_do_id = maproot_doId - print("Maproot DO ID = %d" % (maproot_doId, )) + self.maproot_distobjs = set() + print("LoginManagerUD view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - def login(self, username, password): - print("Received login request") - if self.maproot_do_id != None: + def login(self, sender, username, password): + print("Received login request for %d" % (sender, )) + if len(self.maproot_distobjs) > 0: if username == "guest" and password == "guest": - print("Logging in successfully") + # FIXME: Set client into ESTABLISHED state! + print(" Logging in successfully") + maproot_for_client = random.choice(list(self.maproot_distobjs)) + self.repo.distobj_by_do_id(maproot_for_client).create_avatar(sender, sender) else: # Bad credentials # FIXME: Implement - print("Disconnecting for bad credentials") + print(" Disconnecting for bad credentials") else: # maproot hasn't contacted us yet. # FIXME: ...or has left, and no replacement has arrived. # FIXME: Implement a disconnection with reason "game not up yet". print("Dropping connection attempt due to missing maproot") + def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): + if (new_parent == LOGIN_MANAGER_DO_ID) and (new_zone == MAP_ROOT_ZONE): + # A new maproot "service" has entered + self.maproot_distobjs.add(do_id) + print("LoginManagerUD added %d to maproot services." % (do_id, )) + elif (old_parent == LOGIN_MANAGER_DO_ID) and (old_zone == MAP_ROOT_ZONE): + # A maproot has just left + self.maproot_distobjs.remove(do_id) + print("LoginManagerUD removed %d from maproot services." % (do_id, )) + # ------------------------------------------------------------------- # DistributedMaproot # * has all avatars in its zone 0 @@ -65,14 +77,26 @@ class DistributedMaproot(DistributedObject): class DistributedMaprootAI(DistributedObject): def init(self): - print("DistributedMaprootAI view created") + print("DistributedMaprootAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) # FIXME: ENTER astrond DO # Register with LoginManager - self.login_manager = self.repo.create_distobjglobal_view('LoginManagerAI', LOGIN_MANAGER_DO_ID) + # self.login_manager = self.repo.create_distobjglobal_view('LoginManagerAI', LOGIN_MANAGER_DO_ID) # self.login_manager.set_maproot(self.do_id) + def create_avatar(self, sender, client_id): + print("%d called DistributedMaprootAI.create_avatar(%d)" % (sender, client_id)) + +class DistributedMaprootAE(DistributedObject): + def init(self): + print("DistributedMaprootAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + + def create_avatar(self, sender, client_id): + print("DistributedMaprootAE.create_avatar(sender %d, client_id %d)" % (sender, client_id)) + self.send_update('create_avatar', client_id) + class DistributedMaprootUD(DistributedObject): - pass + def init(self): + print("DistributedMaprootUD view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) # ------------------------------------------------------------------- # DistributedAvatar From 43ab1306ccb85ad8585e4a7ecbc9e0834748815a Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Mon, 3 Nov 2014 18:22:51 +0100 Subject: [PATCH 18/33] Use correct field id in SET_FIELD messages. --- astron/distributed_object.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 1433110..31028f5 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -14,6 +14,8 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): for dmethod_id in range(0, self.dclass.num_fields())]) self.dmethod_id_to_name = dict([(dmethod_id, self.dclass.get_field(dmethod_id).name()) for dmethod_id in range(0, self.dclass.num_fields())]) + self.field_id_to_dmethod_id = dict([(self.dclass.get_field(dmethod_id).id(), dmethod_id) + for dmethod_id in range(0, self.dclass.num_fields())]) self.do_id = do_id self.parent = parent_id self.zone = zone_id @@ -59,7 +61,7 @@ def acquire_ai(self): def update_field(self, sender, field_id, dgi): """Handles incoming SET_FIELD updates.""" decoded_args = [] - field = self.dclass.get_field(field_id) + field = self.dclass.get_field(self.field_id_to_dmethod_id[field_id]) num_args = field.type().as_method().num_parameters() for arg_id in range(0, num_args): arg = field.type().as_method().get_parameter(arg_id) @@ -88,12 +90,12 @@ def send_update(self, field_name, *values): dg = self.repo.create_message_stub(self.do_id, self.do_id) dg.add_int16(servermsg.STATESERVER_OBJECT_SET_FIELD) dg.add_int32(self.do_id) - dg.add_int16(dmethod_id) + dg.add_int16(field.id()) for arg_id in range(0, num_args): arg = field.type().as_method().get_parameter(arg_id) arg_type = arg.type().subtype() if arg_type == module.kTypeStruct: - self.pack_struct(dg, arg.type().as_struct(), *values[arg_id]) + self.pack_struct(dg, arg. type().as_struct(), *values[arg_id]) else: self.type_packer[arg_type](dg, values[arg_id]) self.repo.send_datagram(dg) From 199b2eb36ed24d12f52632194a0ec057014ea934 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Mon, 3 Nov 2014 20:09:01 +0100 Subject: [PATCH 19/33] Added dbss channel to InternalRepository. Tentative stubs for DBSS_CREATE_OBJECT*. Added sqlite3 db to example. --- astron/object_repository.py | 37 +++++++++++++++++++++-- example/transitional/astrond.yml | 14 +++++++++ example/transitional/example_services.py | 2 +- example/transitional/example_world.py | 2 +- example/transitional/shared_constants.py | 6 +++- example/transitional/simple_example.db | Bin 0 -> 5120 bytes example/transitional/simple_example.py | 6 ++-- 7 files changed, 60 insertions(+), 7 deletions(-) create mode 100644 example/transitional/simple_example.db diff --git a/astron/object_repository.py b/astron/object_repository.py index 0be5f4c..3877621 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -205,9 +205,10 @@ def fire_callback(self, resp_msg_type, context): return callback class InternalRepository(ObjectRepository): - def __init__(self, version_string, dcfilename=default_dcfilename, stateserver=400000, ai_channel=500000): + def __init__(self, version_string, dcfilename=default_dcfilename, stateserver = 400000, dbss = 400001, ai_channel=500000): ObjectRepository.__init__(self, dcfilename=dcfilename) self.stateserver = stateserver + self.dbss = dbss self.ai_channel = ai_channel self.msg_type = MSG_TYPE_INTERNAL self.handlers.update({ @@ -266,6 +267,16 @@ def create_distobj(self, cls_name, do_id, parent_id, zone_id, set_ai = False): if set_ai: self.send_STATESERVER_OBJECT_SET_AI(do_id) + def create_distobj_db(self, cls_name, parent_id, zone_ai, set_ai = True): + dclass_id = self.dclass_name_to_id[cls_name] + context = self.register_callback(servermsg.DBSERVER_CREATE_OBJECT, + self.create_distobj_db_callback, + args = [parent_id, zone_ai, set_ai]) + self.send_DBSERVER_CREATE_OBJECT(dclass_id, context) + + def create_distobj_db_callback(self, do_id, parent_id, zone_ai, set_ai): + print(" DB distobj %d created, now moving into (%d, %d), setting AI? %s" % (do_id, parent_id, zone_ai, str(set_ai))) + # Sending messages @@ -301,7 +312,7 @@ def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(self, dclass_id, do_id, parent, self.send_datagram(dg) def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER(self): - dg = self.repo.create_message_stub(self.do_id, self.stateserver) + dg = self.create_message_stub(self.do_id, self.stateserver) dg.add_uint16(servermsg.STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER) dg.add_uint32(self.do_id) dg.add_uint32(self.parent) @@ -311,6 +322,22 @@ def send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED_OTHER(self): # FIXME: Add OTHER fields self.send_datagram(dg) + def send_DBSERVER_CREATE_OBJECT(self, dclass_id, context): + dg = self.create_message_stub(self.ai_channel, self.dbss) + dg.add_uint16(servermsg.DBSERVER_CREATE_OBJECT) + dg.add_uint32(context) + dg.add_uint16(dclass_id) + # FIXME: `uint16 field_count`, `[uint16 field_id, ]*field_count` + self.send_datagram(dg) + + def send_CLIENTAGENT_SET_STATE(self, clientagent, ca_state, sender = 0): + if sender == 0: + sender = self.ai_channel + dg = self.create_message_stub(sender, clientagent) + dg.add_uint16(servermsg.CLIENTAGENT_SET_STATE) + dg.add_uint16(ca_state) + self.send_datagram(dg) + # Receive messages def handle_STATESERVER_OBJECT_SET_FIELD(self, dgi, sender, recipients): @@ -344,6 +371,12 @@ def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, sender, recipien print("handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED", sender, recipients) self.create_view_from_datagram(dgi, cls_postfix = 'AI') + def handle_DBSERVER_CREATE_OBJECT_RESP(self, dgi, sender, recipients): + context = dgi.read_uint32() + do_id = dgi.read_uint32() + callback, args, kwargs = self.fire_callback(servermsg.DBSERVER_CREATE_OBJECT_RESP, context) + callback(do_id, *args, **kwargs) + class ClientRepository(ObjectRepository): def __init__(self, version_string, dcfilename=default_dcfilename): ObjectRepository.__init__(self, dcfilename=dcfilename) diff --git a/example/transitional/astrond.yml b/example/transitional/astrond.yml index dd47d36..9bec020 100644 --- a/example/transitional/astrond.yml +++ b/example/transitional/astrond.yml @@ -36,6 +36,20 @@ roles: - type: stateserver control: 402000 + - type: database + control: 402001 + generate: + min: 100000 # Required (no default) + backend: + type: sqlite3 + database: ./simple_example.db + + - type: dbss + database: 402001 # The channel of the associated database + ranges: + - min: 100000 + + - type: eventlogger bind: 127.0.0.1:9090 # REMEMBER: UDP output: ./events-%Y-%m-%d.log diff --git a/example/transitional/example_services.py b/example/transitional/example_services.py index 01a39ee..9da67b5 100755 --- a/example/transitional/example_services.py +++ b/example/transitional/example_services.py @@ -6,7 +6,7 @@ from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE if __name__ == '__main__': - repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500000) + repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, dbss = 402001, ai_channel=500000) def connected(): print('Connection established.') diff --git a/example/transitional/example_world.py b/example/transitional/example_world.py index 64489e1..36f2f6e 100755 --- a/example/transitional/example_world.py +++ b/example/transitional/example_world.py @@ -6,7 +6,7 @@ from shared_constants import MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE if __name__ == '__main__': - repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, ai_channel=500001) + repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', stateserver=402000, dbss = 402001, ai_channel=500001) def connected(): print('Connection established.') diff --git a/example/transitional/shared_constants.py b/example/transitional/shared_constants.py index 1c329a0..ec798ce 100644 --- a/example/transitional/shared_constants.py +++ b/example/transitional/shared_constants.py @@ -3,4 +3,8 @@ MAP_ROOT_DO_ID = 10000 MAP_ROOT_PARENT = LOGIN_MANAGER_DO_ID MAP_ROOT_ZONE = 0 -MAP_ROOT_LOCATION = MAP_ROOT_PARENT * 2**32 | MAP_ROOT_ZONE \ No newline at end of file +MAP_ROOT_LOCATION = MAP_ROOT_PARENT * 2**32 | MAP_ROOT_ZONE + +AVATARS_PARENT = LOGIN_MANAGER_DO_ID +AVATARS_ZONE = 1 +AVATARS_LOCATION = LOGIN_MANAGER_DO_ID * 2**32 | AVATARS_ZONE \ No newline at end of file diff --git a/example/transitional/simple_example.db b/example/transitional/simple_example.db new file mode 100644 index 0000000000000000000000000000000000000000..0a3c15c8e6bc6026288e7aa1fe524439dcb03eb1 GIT binary patch literal 5120 zcmeH|K~KUk6vx}XqQiv56C60$iwPtUgIqj1aEZhLI?;r9SPD!s15CGKyz-g2`whJM z5j>iB^1{JwHUv#jJWBeK_W$RD2;Rm?2802>S3urf{$9QGjO^C9t2Jxg;p&? zZyBtmS4@M+Aj`QuR%^6aqZy71(`2Vst*%>bc4D*(Y{Z8SyVR}fv2Nwc`}uiVArPJ) z?ZGO|rfKMn`Ja4|Ze;WrgcJ&Gupi&e8MPNM$Y(>XV{l6ZUsZOB? z{E 0: if username == "guest" and password == "guest": - # FIXME: Set client into ESTABLISHED state! + # Login successful + self.repo.send_CLIENTAGENT_SET_STATE(sender, 2, sender = self.do_id) print(" Logging in successfully") maproot_for_client = random.choice(list(self.maproot_distobjs)) self.repo.distobj_by_do_id(maproot_for_client).create_avatar(sender, sender) @@ -85,6 +86,7 @@ def init(self): def create_avatar(self, sender, client_id): print("%d called DistributedMaprootAI.create_avatar(%d)" % (sender, client_id)) + self.repo.create_distobj_db('DistributedMaproot', AVATARS_PARENT, AVATARS_ZONE, set_ai = True) class DistributedMaprootAE(DistributedObject): def init(self): From 9f92f712dbbc747056d1a529490a1065549b11e1 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Mon, 3 Nov 2014 22:45:12 +0100 Subject: [PATCH 20/33] Moved all Magic Numbers in the example into shared_constants.py. Cleanup. --- astron/connection.py | 2 -- astron/helpers.py | 7 +++++++ astron/object_repository.py | 23 ++++++----------------- example/transitional/example_client.py | 2 +- example/transitional/example_services.py | 7 +++++-- example/transitional/example_world.py | 7 +++++-- example/transitional/shared_constants.py | 8 +++++++- 7 files changed, 31 insertions(+), 25 deletions(-) create mode 100644 astron/helpers.py diff --git a/astron/connection.py b/astron/connection.py index 2c80876..acdcdb8 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -41,8 +41,6 @@ def poll_datagram(self): self.read() # Did we just finish reading the message length? if (not self.reading_message) and (self.remaining_length == 0): - # FIXME: Truncate partial data if you have more than needed, you dolt! - # This should be done in read() anyway, why is EVERYTHING read?? length = struct.unpack(' Date: Mon, 3 Nov 2014 23:22:44 +0100 Subject: [PATCH 21/33] Established sane ranges for channels. --- example/transitional/astrond.yml | 15 +++++------ example/transitional/shared_constants.py | 32 ++++++++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/example/transitional/astrond.yml b/example/transitional/astrond.yml index 9bec020..583c0f1 100644 --- a/example/transitional/astrond.yml +++ b/example/transitional/astrond.yml @@ -9,7 +9,7 @@ general: # Actually just DOGs, not *the* UberDOG. uberdogs: - - id: 1234 + - id: 20000 class: LoginManager anonymous: true # May be contacted by status New clients to be Established @@ -30,25 +30,26 @@ roles: add_interest: disabled # Channels defines the range of channels this clientagent can assign to Clients channels: - min: 100100 - max: 299999 + min: 100000 + max: 999999 - type: stateserver - control: 402000 + control: 1000 - type: database - control: 402001 + control: 1001 generate: min: 100000 # Required (no default) + max: 4294967295 backend: type: sqlite3 database: ./simple_example.db - type: dbss - database: 402001 # The channel of the associated database + database: 1001 # The channel of the associated database ranges: - min: 100000 - + max: 4294967295 - type: eventlogger bind: 127.0.0.1:9090 # REMEMBER: UDP diff --git a/example/transitional/shared_constants.py b/example/transitional/shared_constants.py index 937097b..67b6b71 100644 --- a/example/transitional/shared_constants.py +++ b/example/transitional/shared_constants.py @@ -1,16 +1,28 @@ -LOGIN_MANAGER_DO_ID = 1234 +from astron.helpers import parent_zone_to_location -MAP_ROOT_DO_ID = 10000 +# 1,000 - 9,999: Roles +COMMON_STATESERVER = 1000 +COMMON_DBSS = 1001 + +# 10,000 - 19,999: Internal Repositories +SERVICES = 10000 +WORLD = 10001 + +# 20,000 - 99,999: Fixed-ID Distributed Objects in StateServer +LOGIN_MANAGER_DO_ID = 20000 +# The increasingly inaccurately named MapRoot is the representative +# Distributed Object for the repository that AIs for player +# characters. +# FIXME: These need more flexible assignment, so that several +# InternalRepos can share a pool of DO IDs. +MAP_ROOT_DO_ID = 21000 MAP_ROOT_PARENT = LOGIN_MANAGER_DO_ID MAP_ROOT_ZONE = 0 -MAP_ROOT_LOCATION = MAP_ROOT_PARENT * 2**32 | MAP_ROOT_ZONE +MAP_ROOT_LOCATION = parent_zone_to_location(MAP_ROOT_PARENT, MAP_ROOT_ZONE) + +# 100,000- 999,999:Clients +# 100,000 - 4294967295: Distributed Objects in DBSS AVATARS_PARENT = LOGIN_MANAGER_DO_ID AVATARS_ZONE = 1 -AVATARS_LOCATION = LOGIN_MANAGER_DO_ID * 2**32 | AVATARS_ZONE - -COMMON_STATESERVER = 402000 -COMMON_DBSS = 402001 - -SERVICES = 500000 -WORLD = 500001 +AVATARS_LOCATION = parent_zone_to_location(LOGIN_MANAGER_DO_ID, AVATARS_ZONE) From 928b5a2d8e2eea738061fc56e8375b33800d45a7 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Tue, 4 Nov 2014 00:06:51 +0100 Subject: [PATCH 22/33] Added CLIENTAGENT_EJECT and CLIENTAGENT_DROP. Minor improvements. --- astron/distributed_object.py | 12 ++++++++++++ example/transitional/simple_example.py | 18 +++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 31028f5..3bebfd2 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -198,6 +198,18 @@ def unpack_string(self, dgi): return dgi.read_string() # Sending + + def send_CLIENTAGENT_EJECT(self, client_id, disconnect_code, reason): + dg = self.repo.create_message_stub(self.do_id, client_id) + dg.add_uint16(servermsg.CLIENTAGENT_EJECT) + dg.add_uint16(disconnect_code) + dg.add_string(reason) + self.repo.send_datagram(dg) + + def send_CLIENTAGENT_DROP(self, client_id): + dg = self.repo.create_message_stub(self.do_id, client_id) + dg.add_uint16(servermsg.CLIENTAGENT_DROP) + self.repo.send_datagram(dg) # Handle def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): diff --git a/example/transitional/simple_example.py b/example/transitional/simple_example.py index 329783b..2c07254 100644 --- a/example/transitional/simple_example.py +++ b/example/transitional/simple_example.py @@ -49,12 +49,13 @@ def login(self, sender, username, password): maproot_for_client = random.choice(list(self.maproot_distobjs)) self.repo.distobj_by_do_id(maproot_for_client).create_avatar(sender, sender) else: # Bad credentials - # FIXME: Implement + self.send_CLIENTAGENT_EJECT(sender, 122, "Bad credentials") print(" Disconnecting for bad credentials") else: # maproot hasn't contacted us yet. # FIXME: ...or has left, and no replacement has arrived. # FIXME: Implement a disconnection with reason "game not up yet". + self.send_CLIENTAGENT_EJECT(sender, 999, "Server isn't ready") print("Dropping connection attempt due to missing maproot") def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): @@ -79,14 +80,10 @@ class DistributedMaproot(DistributedObject): class DistributedMaprootAI(DistributedObject): def init(self): print("DistributedMaprootAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - # FIXME: ENTER astrond DO - # Register with LoginManager - # self.login_manager = self.repo.create_distobjglobal_view('LoginManagerAI', LOGIN_MANAGER_DO_ID) - # self.login_manager.set_maproot(self.do_id) def create_avatar(self, sender, client_id): print("%d called DistributedMaprootAI.create_avatar(%d)" % (sender, client_id)) - self.repo.create_distobj_db('DistributedMaproot', AVATARS_PARENT, AVATARS_ZONE, set_ai = True) + self.repo.create_distobj_db('DistributedAvatar', AVATARS_PARENT, AVATARS_ZONE, set_ai = True) class DistributedMaprootAE(DistributedObject): def init(self): @@ -108,10 +105,13 @@ def init(self): # ------------------------------------------------------------------- class DistributedAvatar(DistributedObject): - pass + def init(self): + print("DistributedAvatar created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) class DistributedAvatarAI(DistributedObject): - pass + def init(self): + print("DistributedAvatarAI created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) class DistributedAvatarOV(DistributedObject): - pass + def init(self): + print("DistributedAvatarOV created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) From 6b8f2fbd39636d427b75cff8e709c419a59c6444 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Tue, 4 Nov 2014 00:20:38 +0100 Subject: [PATCH 23/33] Making the transitional example the actual one. --- example/{transitional => }/astrond.yml | 0 example/example.py | 8 ----- example/{transitional => }/example_client.py | 0 example/example_main.py | 29 ------------------ .../{transitional => }/example_services.py | 0 example/{transitional => }/example_world.py | 0 .../{transitional => }/shared_constants.py | 0 example/{transitional => }/simple_example.db | Bin example/{transitional => }/simple_example.dc | 0 example/{transitional => }/simple_example.py | 0 10 files changed, 37 deletions(-) rename example/{transitional => }/astrond.yml (100%) delete mode 100644 example/example.py rename example/{transitional => }/example_client.py (100%) delete mode 100755 example/example_main.py rename example/{transitional => }/example_services.py (100%) rename example/{transitional => }/example_world.py (100%) rename example/{transitional => }/shared_constants.py (100%) rename example/{transitional => }/simple_example.db (100%) rename example/{transitional => }/simple_example.dc (100%) rename example/{transitional => }/simple_example.py (100%) diff --git a/example/transitional/astrond.yml b/example/astrond.yml similarity index 100% rename from example/transitional/astrond.yml rename to example/astrond.yml diff --git a/example/example.py b/example/example.py deleted file mode 100644 index 8823f45..0000000 --- a/example/example.py +++ /dev/null @@ -1,8 +0,0 @@ -from astron.distributed_object import DistributedObject - -class LoginManager(DistributedObject): - pass - -class LoginManagerUD(DistributedObject): - pass - diff --git a/example/transitional/example_client.py b/example/example_client.py similarity index 100% rename from example/transitional/example_client.py rename to example/example_client.py diff --git a/example/example_main.py b/example/example_main.py deleted file mode 100755 index 375ab94..0000000 --- a/example/example_main.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -from time import sleep - -from astron.object_repository import ClientRepository - -if __name__ == '__main__': - repo = ClientRepository('SimpleExample v0.2', 'example.dc') - - def connected(): - print('Connection established.') - - def ejected(error_code, reason): - print('Got ejected (%i): %s' % (error_code, reason)) - - def failed(): - print('Connection attempt failed.') - - repo.connect(connected, failed, ejected) - - while True: - repo.poll_till_empty() - #print(repo.poll_datagram()) - sleep(1) - -## Lets do some random things -#print mod.get_num_classes() # or GetNumClasses -#cls = mod.get_class_by_name('Foobar') # or getClassByName -#print cls.get_name() # -> 'Foobar' diff --git a/example/transitional/example_services.py b/example/example_services.py similarity index 100% rename from example/transitional/example_services.py rename to example/example_services.py diff --git a/example/transitional/example_world.py b/example/example_world.py similarity index 100% rename from example/transitional/example_world.py rename to example/example_world.py diff --git a/example/transitional/shared_constants.py b/example/shared_constants.py similarity index 100% rename from example/transitional/shared_constants.py rename to example/shared_constants.py diff --git a/example/transitional/simple_example.db b/example/simple_example.db similarity index 100% rename from example/transitional/simple_example.db rename to example/simple_example.db diff --git a/example/transitional/simple_example.dc b/example/simple_example.dc similarity index 100% rename from example/transitional/simple_example.dc rename to example/simple_example.dc diff --git a/example/transitional/simple_example.py b/example/simple_example.py similarity index 100% rename from example/transitional/simple_example.py rename to example/simple_example.py From 4711d683cd689cc00010b0a5532f658b5b7b8a2d Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Tue, 4 Nov 2014 00:28:30 +0100 Subject: [PATCH 24/33] Renamed things that were named simple_example. --- astron/connection.py | 1 - astron/object_repository.py | 1 + astrond.yml | 13 ------------- example/astrond.yml | 4 ++-- example/{simple_example.db => example.db} | Bin example/{simple_example.dc => example.dc} | 6 +++--- example/example_client.py | 2 +- example/example_services.py | 2 +- example/{simple_example.py => example_views.py} | 6 +++--- example/example_world.py | 2 +- 10 files changed, 12 insertions(+), 25 deletions(-) delete mode 100644 astrond.yml rename example/{simple_example.db => example.db} (100%) rename example/{simple_example.dc => example.dc} (84%) rename example/{simple_example.py => example_views.py} (96%) diff --git a/astron/connection.py b/astron/connection.py index acdcdb8..97042fd 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -61,7 +61,6 @@ def poll_datagram(self): def read(self): try: - #print("Blocking: %s" % (str(self.socket.), )) data = self.socket.recv(self.remaining_length) # Has the connection been closed? if len(data) == 0: diff --git a/astron/object_repository.py b/astron/object_repository.py index 829712a..6d3f1ff 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -266,6 +266,7 @@ def create_distobj_db(self, cls_name, parent_id, zone_ai, set_ai = True): def create_distobj_db_callback(self, do_id, parent_id, zone_ai, set_ai): print(" DB distobj %d created, now moving into (%d, %d), setting AI? %s" % (do_id, parent_id, zone_ai, str(set_ai))) # FIXME: DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS and STATESERVER_OBJECT_SET_LOCATION + # FIXME: Do SET_AI if requested # Sending messages diff --git a/astrond.yml b/astrond.yml deleted file mode 100644 index b3461d8..0000000 --- a/astrond.yml +++ /dev/null @@ -1,13 +0,0 @@ - -general: - dc_files: ['simple_example.dc'] - -messagedirector: - bind: 0.0.0.0:7199 - -roles: - - type: clientagent - version: 'SimpleExample v0.2' - channels: - min: 100100 - max: 100999 diff --git a/example/astrond.yml b/example/astrond.yml index 583c0f1..0465db3 100644 --- a/example/astrond.yml +++ b/example/astrond.yml @@ -5,7 +5,7 @@ daemon: general: eventlogger: 127.0.0.1:9090 dc_files: - - simple_example.dc + - example.dc # Actually just DOGs, not *the* UberDOG. uberdogs: @@ -43,7 +43,7 @@ roles: max: 4294967295 backend: type: sqlite3 - database: ./simple_example.db + database: ./example.db - type: dbss database: 1001 # The channel of the associated database diff --git a/example/simple_example.db b/example/example.db similarity index 100% rename from example/simple_example.db rename to example/example.db diff --git a/example/simple_example.dc b/example/example.dc similarity index 84% rename from example/simple_example.dc rename to example/example.dc index bfdb7e8..0f70904 100644 --- a/example/simple_example.dc +++ b/example/example.dc @@ -4,9 +4,9 @@ typedef uint32 zoneId; typedef uint64 channel; // The Python Views for these distributed classes. -from simple_example import LoginManager/AI/UD -from simple_example import DistributedMaproot/AI/UD/AE -from simple_example import DistributedAvatar/AI/OV +from example_views import LoginManager/AI/UD +from example_views import DistributedMaproot/AI/UD/AE +from example_views import DistributedAvatar/AI/OV // A simple DOG for username/password authentication and handoff to // the DistributedMaproot for avatar creation. diff --git a/example/example_client.py b/example/example_client.py index de0aa29..ccb469f 100755 --- a/example/example_client.py +++ b/example/example_client.py @@ -6,7 +6,7 @@ from shared_constants import LOGIN_MANAGER_DO_ID if __name__ == '__main__': - repo = ClientRepository('SimpleExample v0.2', 'simple_example.dc') + repo = ClientRepository('SimpleExample v0.2', 'example.dc') def connected(): print('Connection established.') diff --git a/example/example_services.py b/example/example_services.py index 1e77c04..2668b56 100755 --- a/example/example_services.py +++ b/example/example_services.py @@ -6,7 +6,7 @@ from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, SERVICES, COMMON_STATESERVER, COMMON_DBSS if __name__ == '__main__': - repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', + repo = InternalRepository('SimpleExample v0.2', 'example.dc', stateserver = COMMON_STATESERVER, dbss = COMMON_DBSS, ai_channel = SERVICES) diff --git a/example/simple_example.py b/example/example_views.py similarity index 96% rename from example/simple_example.py rename to example/example_views.py index 2c07254..8db4b25 100644 --- a/example/simple_example.py +++ b/example/example_views.py @@ -48,13 +48,13 @@ def login(self, sender, username, password): print(" Logging in successfully") maproot_for_client = random.choice(list(self.maproot_distobjs)) self.repo.distobj_by_do_id(maproot_for_client).create_avatar(sender, sender) - else: # Bad credentials + else: + # Bad credentials self.send_CLIENTAGENT_EJECT(sender, 122, "Bad credentials") print(" Disconnecting for bad credentials") else: - # maproot hasn't contacted us yet. + # No maproot has appeared yet. # FIXME: ...or has left, and no replacement has arrived. - # FIXME: Implement a disconnection with reason "game not up yet". self.send_CLIENTAGENT_EJECT(sender, 999, "Server isn't ready") print("Dropping connection attempt due to missing maproot") diff --git a/example/example_world.py b/example/example_world.py index 1cbb1e9..6346e5d 100755 --- a/example/example_world.py +++ b/example/example_world.py @@ -6,7 +6,7 @@ from shared_constants import MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, WORLD, COMMON_STATESERVER, COMMON_DBSS if __name__ == '__main__': - repo = InternalRepository('SimpleExample v0.2', 'simple_example.dc', + repo = InternalRepository('SimpleExample v0.2', 'example.dc', stateserver = COMMON_STATESERVER, dbss = COMMON_DBSS, ai_channel = WORLD) From a88d7461ed5075f5c4b36970ddeb94dddd763fb3 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Thu, 6 Nov 2014 15:06:06 +0100 Subject: [PATCH 25/33] Added set_ai to create_distobjglobal_view(). Cleanups. --- astron/object_repository.py | 47 +++++++++++++++++++++++-------------- example/example_services.py | 6 ++--- example/example_world.py | 6 ++++- 3 files changed, 36 insertions(+), 23 deletions(-) diff --git a/astron/object_repository.py b/astron/object_repository.py index 6d3f1ff..742202b 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -171,12 +171,15 @@ def create_view_from_datagram(self, dgi, cls_postfix = ''): # FIXME: Read the field values from the dgi and apply them dist_obj.init() - def create_distobjglobal_view(self, cls_name, do_id): + def create_distobjglobal_view(self, cls_name, do_id, set_ai = False): cls = self.dclass_name_to_cls[cls_name] dclass_id = self.dclass_name_to_id[cls_name] dist_obj = cls(self, dclass_id, do_id, 0, 0) self.distributed_objects[do_id] = dist_obj dist_obj.init() + # FIXME: Now set interest in that do_id to get messages if you're the "UD" + if set_ai: + self.send_CONTROL_ADD_CHANNEL(do_id) return dist_obj # Callback management for *_RESP messages @@ -209,21 +212,7 @@ def __init__(self, version_string, dcfilename=default_dcfilename, stateserver = # FIXME: Add handlers for incoming messages }) self.global_views = {} - self.repo_interests = set() - def add_ai_interest(self, distobj_id, zone_id): - self.repo_interests.add(parent_zone_to_location(distobj_id, zone_id)) - # FIXME: As do_ids and zones may be of different sizes, - # this calculation has to take that into account. - self.send_CONTROL_ADD_CHANNEL(parent_zone_to_location(distobj_id, zone_id)) - # FIXME: Request list of objects already existing in that - # zone for ENTER. - # FIXME: Messages for DOs that haven't entered yet may come - # over the control channel. Either some kind of solution is - # needed, or AIR interests shall be implemented in Astron as - # actual messages. - # FIXME: There should also be remove_ai_interest(distobj, zone) - def connect(self, connection_success, connection_failure, host=default_host, port=default_client_port): # FIXME: Handle connection failures @@ -256,7 +245,7 @@ def create_distobj(self, cls_name, do_id, parent_id, zone_id, set_ai = False): if set_ai: self.send_STATESERVER_OBJECT_SET_AI(do_id) - def create_distobj_db(self, cls_name, parent_id, zone_ai, set_ai = True): + def create_distobj_db(self, cls_name, parent_id, zone_ai, set_ai = False): dclass_id = self.dclass_name_to_id[cls_name] context = self.register_callback(servermsg.DBSERVER_CREATE_OBJECT, self.create_distobj_db_callback, @@ -342,11 +331,10 @@ def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, dgi, sender, recipients): new_zone = dgi.read_uint32() old_parent = dgi.read_uint32() old_zone = dgi.read_uint32() - # print(" %d moves from (%d, %d) to (%d, %d)" % (do_id, old_parent, old_zone, new_parent, new_zone)) - # FIXME: Now what to do with that information? for recipient in recipients: if recipient in self.distributed_objects.keys(): self.distributed_objects[recipient].handle_STATESERVER_OBJECT_CHANGING_LOCATION(sender, do_id, new_parent, new_zone, old_parent, old_zone) + # FIXME: If the repo has "interest" in either location, that should be handled somehow. def handle_STATESERVER_OBJECT_GET_AI(self, dgi, sender, recipients): print("handle_STATESERVER_OBJECT_GET_AI", sender, recipients) @@ -552,3 +540,26 @@ def handle_CLIENT_ENTER_OBJECT_REQUIRED_OWNER(self, dgi): def handle_CLIENT_ENTER_OBJECT_REQUIRED_OTHER_OWNER(self, dgi): self.create_view_from_datagram(dgi, cls_postfix = 'OV') + +class InterestInternalRepository(InternalRepository): + def __init__(self, *args, **kwargs): + InternalRepository.__init__(self, *args, **kwargs) + self.repo_interests = set() + + def add_ai_interest(self, distobj_id, zone_id): + self.repo_interests.add(parent_zone_to_location(distobj_id, zone_id)) + # FIXME: As do_ids and zones may be of different sizes, + # this calculation has to take that into account. + self.send_CONTROL_ADD_CHANNEL(parent_zone_to_location(distobj_id, zone_id)) + # FIXME: Request list of objects already existing in that + # zone for ENTER. + # self.send_STATESERVER_OBJECT_GET_ZONE_OBJECTS(context, distobj_id, zone_id) + # FIXME: Messages for DOs that haven't entered yet may come + # over the control channel. Either some kind of solution is + # needed, or AIR interests shall be implemented in Astron as + # actual messages. + # FIXME: There should also be remove_ai_interest(distobj, zone) + + def remove_ai_interest(self, context): + # FIXME: Implement + pass \ No newline at end of file diff --git a/example/example_services.py b/example/example_services.py index 2668b56..3f7b3b1 100755 --- a/example/example_services.py +++ b/example/example_services.py @@ -2,7 +2,7 @@ from time import sleep -from astron.object_repository import InternalRepository +from astron.object_repository import InterestInternalRepository as InternalRepository from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, SERVICES, COMMON_STATESERVER, COMMON_DBSS if __name__ == '__main__': @@ -13,9 +13,7 @@ def connected(): print('Connection established.') - login_manager = repo.create_distobjglobal_view('LoginManagerUD', LOGIN_MANAGER_DO_ID) - # FIXME: This should be folded into a 'set_ai = True' kwarg into create_distobjglobal_view - repo.send_CONTROL_ADD_CHANNEL(LOGIN_MANAGER_DO_ID) + repo.create_distobjglobal_view('LoginManagerUD', LOGIN_MANAGER_DO_ID, set_ai = True) repo.add_ai_interest(MAP_ROOT_PARENT, MAP_ROOT_ZONE) def failed(): diff --git a/example/example_world.py b/example/example_world.py index 6346e5d..efcde08 100755 --- a/example/example_world.py +++ b/example/example_world.py @@ -2,10 +2,14 @@ from time import sleep -from astron.object_repository import InternalRepository +from astron.object_repository import InterestInternalRepository as InternalRepository from shared_constants import MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, WORLD, COMMON_STATESERVER, COMMON_DBSS if __name__ == '__main__': + # FIXME: As soon as there are several AI servers, they have to + # "instinctively" choose different control channels. There will + # have to be a) a channel broker service, or b) have to use a + # to-be-designed CONTROL message to get assigned a channel. repo = InternalRepository('SimpleExample v0.2', 'example.dc', stateserver = COMMON_STATESERVER, dbss = COMMON_DBSS, From 305b0b6a49dce6cc17b259c120ad1f72f01203a7 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Thu, 6 Nov 2014 17:45:13 +0100 Subject: [PATCH 26/33] Added README.md for example/ --- example/README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 example/README.md diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000..615ad4d --- /dev/null +++ b/example/README.md @@ -0,0 +1,14 @@ +python-libastron example +======================== + +This is a minimal example of how to build an MMO with Panda3D and Astron. To run it: +* start an astrond with the given config file: astrond astrond.yml +* start the login service: ./example_services.py +* start the AI service: ./example_world.py +* start clients + +Major missing features: +* Preventing multiple logins. +* Merging example_services.py and example_world.py into a generic server process. +* Creating avatars. +* Panda3D bindings. From 7a1a18cb28ace2796de17a683ba300f93a315bd4 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Thu, 6 Nov 2014 18:42:01 +0100 Subject: [PATCH 27/33] Updated /README.md. --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e5dd80..f05c11e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ libastron-python ================ -Work in progress. +Work in progress. Major missing features: +* Packing / unpacking of REQUIRED and OTHER fields. +* Lots of messages +* Interests in InterestInternalRepositories A Python implementation of the application-side of the Astron protocol. Implements ClientRepository and InternalRepository in python. From e0f8f8a488815c7c5d57b6b98b99953fcbe3c38e Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sat, 8 Nov 2014 07:04:12 +0100 Subject: [PATCH 28/33] Removed version_string from InternalRepository (unused). Rewrote example_services.py into nearly-generic server. Removed set_maproot() from views. Added and renamed some constants. --- astron/object_repository.py | 2 +- example/example_services.py | 103 +++++++++++++++++++++++++++++++----- example/example_views.py | 4 -- example/example_world.py | 30 ----------- example/shared_constants.py | 11 ++-- 5 files changed, 98 insertions(+), 52 deletions(-) delete mode 100755 example/example_world.py diff --git a/astron/object_repository.py b/astron/object_repository.py index 742202b..9ebb635 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -197,7 +197,7 @@ def fire_callback(self, resp_msg_type, context): return callback class InternalRepository(ObjectRepository): - def __init__(self, version_string, dcfilename=default_dcfilename, stateserver = 400000, dbss = 400001, ai_channel=500000): + def __init__(self, dcfilename=default_dcfilename, stateserver = 400000, dbss = 400001, ai_channel=500000): ObjectRepository.__init__(self, dcfilename=dcfilename) self.stateserver = stateserver self.dbss = dbss diff --git a/example/example_services.py b/example/example_services.py index 3f7b3b1..fd24967 100755 --- a/example/example_services.py +++ b/example/example_services.py @@ -1,26 +1,101 @@ #!/usr/bin/env python +# TODO +# * Catch SIGSTOP +# * Turn --login and --ai into something more generic +# * Proper logging +# * Monitoring output + +import argparse from time import sleep +import datetime from astron.object_repository import InterestInternalRepository as InternalRepository -from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, SERVICES, COMMON_STATESERVER, COMMON_DBSS +from shared_constants import LOGIN_MANAGER_DO_ID, \ + MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, \ + SERVICES_CHANNEL, STATESERVER, DBSS, \ + DC_FILE, \ + SERVER_FRAMERATE -if __name__ == '__main__': - repo = InternalRepository('SimpleExample v0.2', 'example.dc', - stateserver = COMMON_STATESERVER, - dbss = COMMON_DBSS, - ai_channel = SERVICES) +class AstronServer: + def __init__(self, + dc_file = DC_FILE, + stateserver = STATESERVER, + dbss = DBSS, + ai_channel = SERVICES_CHANNEL, + host = '127.0.0.1', + port = 7199, + frame_time = 1./100., + login = False, + ai = False): + self.host = host + self.port = port + self.frame_time = frame_time + self.login = login + self.ai = ai + self.repo = InternalRepository(dc_file, + stateserver = stateserver, + dbss = dbss, + ai_channel = ai_channel) - def connected(): + def start(self): + self.repo.connect(self.connected, self.failed, host = self.host, port = self.port) + while True: + self.repo.poll_till_empty() + # FIXME: Measure the time left in the frame, and sleep accordingly here. + # FIXM: Log ratio of time left, prevalence of overlong frames, total accumulated lag + sleep(0.1) + + def connected(self): print('Connection established.') - repo.create_distobjglobal_view('LoginManagerUD', LOGIN_MANAGER_DO_ID, set_ai = True) - repo.add_ai_interest(MAP_ROOT_PARENT, MAP_ROOT_ZONE) + # Login server, assigner of AIs + if self.login: + print("Starting Login service") + self.repo.create_distobjglobal_view('LoginManagerUD', LOGIN_MANAGER_DO_ID, set_ai = True) + self.repo.add_ai_interest(MAP_ROOT_PARENT, MAP_ROOT_ZONE) + # AI server + if self.ai: + print("Starting AI service") + self.repo.create_distobj('DistributedMaproot', MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, set_ai = True) - def failed(): + def failed(self): print('Connection attempt failed.') - repo.connect(connected, failed, host = '127.0.0.1', port = 7199) +if __name__ == '__main__': + # FIXME: Add an epilog, at least an example usage + parser = argparse.ArgumentParser(description='A generic server process for Astron networks.', + epilog="") + parser.add_argument('-D', '--dcfile', type = str, default = DC_FILE, + help='Distributed Classes definitions file') + parser.add_argument('-H', '--host', type = str, default = '127.0.0.1', + help='astrond host') + parser.add_argument('-P', '--port', type = int, default = 7199, + help='astrond port for message directors') + parser.add_argument('-c', '--channel', type = int, default = SERVICES_CHANNEL, + help='Repository control channel') + parser.add_argument('-s', '--stateserver', type = int, default = STATESERVER, + help='Number of cycles per second to aim for') + parser.add_argument('-d', '--dbss', type = int, default = DBSS, + help='Number of cycles per second to aim for') + parser.add_argument('-r', '--framerate', type = float, default = SERVER_FRAMERATE, + help='Number of cycles per second to aim for') - while True: - repo.poll_till_empty() - sleep(0.1) + # FIXME: These are specific to this application. Considering how + # generic they are, they *should* be convertible into more + # generic arguments. Maybe these are the positional args? + parser.add_argument('-l', '--login', action = "store_true", + help='Login service') + parser.add_argument('-a', '--ai', action = "store_true", + help='AI service') + args = parser.parse_args() + + server = AstronServer(dc_file = args.dcfile, + stateserver = STATESERVER, + dbss = DBSS, + ai_channel = args.channel, + host = args.host, + port = args.port, + frame_time = 1. / args.framerate, + login = args.login, + ai = args.ai) + server.start() diff --git a/example/example_views.py b/example/example_views.py index 8db4b25..e55f020 100644 --- a/example/example_views.py +++ b/example/example_views.py @@ -30,10 +30,6 @@ class LoginManagerAI(DistributedObject): def init(self): print("LoginManagerAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - #def set_maproot(self, maproot_doId): - # print("LoginManagerAI view sends set_maproot") - # self.send_update("set_maproot", maproot_doId) - class LoginManagerUD(DistributedObject): def init(self): self.maproot_distobjs = set() diff --git a/example/example_world.py b/example/example_world.py deleted file mode 100755 index efcde08..0000000 --- a/example/example_world.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -from time import sleep - -from astron.object_repository import InterestInternalRepository as InternalRepository -from shared_constants import MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, WORLD, COMMON_STATESERVER, COMMON_DBSS - -if __name__ == '__main__': - # FIXME: As soon as there are several AI servers, they have to - # "instinctively" choose different control channels. There will - # have to be a) a channel broker service, or b) have to use a - # to-be-designed CONTROL message to get assigned a channel. - repo = InternalRepository('SimpleExample v0.2', 'example.dc', - stateserver = COMMON_STATESERVER, - dbss = COMMON_DBSS, - ai_channel = WORLD) - - def connected(): - print('Connection established.') - repo.create_distobj('DistributedMaproot', MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, set_ai = True) - - def failed(): - print('Connection attempt failed.') - - repo.connect(connected, failed, host = '127.0.0.1', port = 7199) - - while True: - # print("Polling...") - repo.poll_till_empty() - sleep(0.1) diff --git a/example/shared_constants.py b/example/shared_constants.py index 67b6b71..ff17d50 100644 --- a/example/shared_constants.py +++ b/example/shared_constants.py @@ -1,11 +1,16 @@ from astron.helpers import parent_zone_to_location +VERSION_STRING = 'SimpleExample v0.2' +DC_FILE = 'example.dc' +SERVER_FRAMERATE = 120.0 + +# Channels # 1,000 - 9,999: Roles -COMMON_STATESERVER = 1000 -COMMON_DBSS = 1001 +STATESERVER = 1000 +DBSS = 1001 # 10,000 - 19,999: Internal Repositories -SERVICES = 10000 +SERVICES_CHANNEL = 10000 WORLD = 10001 # 20,000 - 99,999: Fixed-ID Distributed Objects in StateServer From 36ce340cc6e3a183271957dc12aa87f751a806cb Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sat, 8 Nov 2014 14:22:30 +0100 Subject: [PATCH 29/33] Use binary operators instead of arithmetic for parent/zone<->location conversion. --- astron/helpers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/astron/helpers.py b/astron/helpers.py index 0eee166..0b8b5ef 100644 --- a/astron/helpers.py +++ b/astron/helpers.py @@ -1,7 +1,7 @@ # FIXME: This needs to acknowledge the fact that there may be 128 bit # locations (64 bit do_ids and zones). def parent_zone_to_location(parent, zone): - return parent * 2**32 | zone + return (parent << 32) | zone def location_to_parent_zone(location): - return (location / 2**32, location % 2**32) + return (location >> 32, location % (2 << 32)) From 80dc918dd9d9a7536bfcaac1fc75a6ee230e2875 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sat, 8 Nov 2014 22:19:18 +0100 Subject: [PATCH 30/33] Many things have happened. --- .gitignore | 1 + astron/distributed_object.py | 17 ++++++- astron/helpers.py | 39 +++++++++++++++ astron/object_repository.py | 97 ++++++++++++++++++++++++++++-------- example/astrond.yml | 4 +- example/example_services.py | 1 + example/example_views.py | 12 ++++- 7 files changed, 144 insertions(+), 27 deletions(-) diff --git a/.gitignore b/.gitignore index 9a7415b..3e9461e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ .pydevproject .gitignore *.log* +*.db diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 3bebfd2..4b879d2 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -1,9 +1,12 @@ +# TODO: Split DistributedObject into ClientObject and InternalObject + from bamboo import module from bamboo.wire import Datagram from pprint import pprint import client_messages as clientmsg import internal_messages as servermsg from astron.object_repository import MSG_TYPE_CLIENT, MSG_TYPE_INTERNAL +from astron.helpers import separate_fields class DistributedObject: def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): @@ -47,11 +50,21 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): module.kTypeString: self.unpack_string, module.kTypeVarstring: self.unpack_string, } + self.required_fields, self.other_fields = separate_fields(self.dclass, ["required"]) + # FIXME: Remove after debug + print("Initing %s %d" % (self.dclass.name(), self.do_id)) + print(" REQUIRED fields: %s" % (" ".join([str(idx) for idx in self.required_fields]), )) + print(" OTHER fields: %s" % (" ".join([str(idx) for idx in self.other_fields]), )) + + # Creating and destroying the view. def init(self): + """Overwrite this to execute code right after view creation.""" print("DO created without custom init(): %d (%s)" % (self.do_id, str(type(self)))) def delete(self): + """Overwrite this to execute code just before a views deletion.""" + # FIXME: Redup in object_repository if the docstring is actually accurate. print("DO deleted: %d" % (self.do_id, )) def acquire_ai(self): @@ -100,6 +113,8 @@ def send_update(self, field_name, *values): self.type_packer[arg_type](dg, values[arg_id]) self.repo.send_datagram(dg) + # Packing and unpacking field data. + def pack_struct(self, dg, struct, *values): num_args = struct.num_fields() if num_args != len(values): @@ -210,7 +225,7 @@ def send_CLIENTAGENT_DROP(self, client_id): dg = self.repo.create_message_stub(self.do_id, client_id) dg.add_uint16(servermsg.CLIENTAGENT_DROP) self.repo.send_datagram(dg) - + # Handle def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): """Override this to react to STATESERVER_OBJECT_CHANGING_LOCATION messages.""" diff --git a/astron/helpers.py b/astron/helpers.py index 0b8b5ef..506c8c5 100644 --- a/astron/helpers.py +++ b/astron/helpers.py @@ -5,3 +5,42 @@ def parent_zone_to_location(parent, zone): def location_to_parent_zone(location): return (location >> 32, location % (2 << 32)) + +# Separate fields by keywords. + +def field_has_keyword(field, keywords): + """For internal use. Determines whether the field has any of + the given keywords.""" + for keyword in keywords: + if field.has_keyword(keyword): + return True + return False + + +def separate_fields(dclass, *preconditions): + """Separate fields into lists based on the presence of keywords. + preconditions are lists of keywords. + This method returns a list of field IDs in ascending order + where each field is in the first list that corresponds with a + precondition where the field has a keyword named in the list. + If it has no keyword named in the preconditions, it will be + filed into an additional slot. For instance, calling + separate_fields(["required", "db"], ["ram"]) + will return a tuple with three lists, where the first list + contains the indices of all fields that have either the + keyword "required" or "db", the second has "ram", but neither + "required" or "db", and the third has the indices of fields + that have none of "required", "db" or "ram". + """ + sorted_fields = [[] for _ in range(0, len(preconditions) + 1)] + for fld_index in range(0, dclass.num_fields()): + field = dclass.get_field(fld_index) + field_is_sorted = False + for precon_index in range(0, len(preconditions)): + if field_has_keyword(field, preconditions[precon_index]): + sorted_fields[precon_index].append(fld_index) + field_is_sorted = True + break + if not field_is_sorted: + sorted_fields[-1].append(fld_index) + return tuple(sorted_fields) diff --git a/astron/object_repository.py b/astron/object_repository.py index 9ebb635..381e7af 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -6,7 +6,7 @@ from connection import Connection import client_messages as clientmsg import internal_messages as servermsg -from helpers import parent_zone_to_location, location_to_parent_zone +from helpers import parent_zone_to_location, separate_fields import importlib DATAGRAM_SIZE = 2 @@ -204,11 +204,12 @@ def __init__(self, dcfilename=default_dcfilename, stateserver = 400000, dbss = 4 self.ai_channel = ai_channel self.msg_type = MSG_TYPE_INTERNAL self.handlers.update({ - servermsg.STATESERVER_OBJECT_SET_FIELD: self.handle_STATESERVER_OBJECT_SET_FIELD, - servermsg.STATESERVER_OBJECT_CHANGING_LOCATION: self.handle_STATESERVER_OBJECT_CHANGING_LOCATION, - servermsg.STATESERVER_OBJECT_GET_AI: self.handle_STATESERVER_OBJECT_GET_AI, + servermsg.STATESERVER_OBJECT_SET_FIELD : self.handle_STATESERVER_OBJECT_SET_FIELD, + servermsg.STATESERVER_OBJECT_CHANGING_LOCATION : self.handle_STATESERVER_OBJECT_CHANGING_LOCATION, + servermsg.STATESERVER_OBJECT_GET_AI : self.handle_STATESERVER_OBJECT_GET_AI, servermsg.STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED: self.handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED, - servermsg.STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED: self.handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED, + servermsg.STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED : self.handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED, + servermsg.DBSERVER_CREATE_OBJECT_RESP : self.handle_DBSERVER_CREATE_OBJECT_RESP, # FIXME: Add handlers for incoming messages }) self.global_views = {} @@ -220,14 +221,6 @@ def connect(self, connection_success, connection_failure, self.send_CONTROL_ADD_CHANNEL(self.ai_channel) connection_success() - def create_message_stub(self, sender, *recipients): - dg = Datagram() - dg.add_uint8(len(recipients)) - for recipient in recipients: - dg.add_uint64(recipient) - dg.add_uint64(sender) - return dg - def handle_datagram(self, dg): dgi = DatagramIterator(dg) num_recipients = dgi.read_uint8() @@ -239,23 +232,44 @@ def handle_datagram(self, dg): else: print("Received unhandled message type " + str(msgtype)) + def create_message_stub(self, sender, *recipients): + dg = Datagram() + dg.add_uint8(len(recipients)) + for recipient in recipients: + dg.add_uint64(recipient) + dg.add_uint64(sender) + return dg + + # Creating views and/or distobjs + def create_distobj(self, cls_name, do_id, parent_id, zone_id, set_ai = False): dclass_id = self.dclass_name_to_id[cls_name] self.send_STATESERVER_CREATE_OBJECT_WITH_REQUIRED(dclass_id, do_id, parent_id, zone_id) if set_ai: self.send_STATESERVER_OBJECT_SET_AI(do_id) - def create_distobj_db(self, cls_name, parent_id, zone_ai, set_ai = False): + def create_distobj_db(self, cls_name, parent_id, zone_ai, set_ai = False, creation_callback = False, additional_args = []): dclass_id = self.dclass_name_to_id[cls_name] - context = self.register_callback(servermsg.DBSERVER_CREATE_OBJECT, - self.create_distobj_db_callback, - args = [parent_id, zone_ai, set_ai]) + if not creation_callback: + context = self.register_callback(servermsg.DBSERVER_CREATE_OBJECT, + self.create_distobj_db_callback, + args = [parent_id, zone_ai, set_ai]) + else: + context = self.register_callback(servermsg.DBSERVER_CREATE_OBJECT, + self.create_distobj_db_callback, + args = [parent_id, zone_ai, set_ai, creation_callback, additional_args]) self.send_DBSERVER_CREATE_OBJECT(dclass_id, context) - def create_distobj_db_callback(self, do_id, parent_id, zone_ai, set_ai): - print(" DB distobj %d created, now moving into (%d, %d), setting AI? %s" % (do_id, parent_id, zone_ai, str(set_ai))) - # FIXME: DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS and STATESERVER_OBJECT_SET_LOCATION + def create_distobj_db_callback(self, do_id, parent_id, zone_id, set_ai, creation_callback = False, additional_args = []): + """For internal use only. Should activate a DB object after its creation.""" + print(" DB distobj %d created, now moving into (%d, %d), setting AI? %s" % (do_id, parent_id, zone_id, str(set_ai))) + self.send_DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS(do_id, parent_id, zone_id) + if set_ai: + self.send_STATESERVER_OBJECT_SET_AI(do_id) + # FIXME: STATESERVER_OBJECT_SET_LOCATION not required? # FIXME: Do SET_AI if requested + if creation_callback: + creation_callback(do_id, parent_id, zone_id, set_ai, *additional_args) # Sending messages @@ -306,9 +320,19 @@ def send_DBSERVER_CREATE_OBJECT(self, dclass_id, context): dg.add_uint16(servermsg.DBSERVER_CREATE_OBJECT) dg.add_uint32(context) dg.add_uint16(dclass_id) - # FIXME: `uint16 field_count`, `[uint16 field_id, ]*field_count` + # FIXME: This is actually `uint16 field_count`, `[uint16 field_id, ]*field_count` + # and should be accessible via create_distobj_db + dg.add_uint16(0) self.send_datagram(dg) + def send_DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS(self, do_id, parent_id, zone_id): + dg = self.create_message_stub(self.ai_channel, do_id) + dg.add_uint16(servermsg.DBSS_OBJECT_ACTIVATE_WITH_DEFAULTS) + dg.add_uint32(do_id) + dg.add_uint32(parent_id) + dg.add_uint32(zone_id) + self.send_datagram(dg) + def send_CLIENTAGENT_SET_STATE(self, clientagent, ca_state, sender = 0): if sender == 0: sender = self.ai_channel @@ -316,6 +340,26 @@ def send_CLIENTAGENT_SET_STATE(self, clientagent, ca_state, sender = 0): dg.add_uint16(servermsg.CLIENTAGENT_SET_STATE) dg.add_uint16(ca_state) self.send_datagram(dg) + + def send_CLIENTAGENT_ADD_SESSION_OBJECT(self, do_id, client_channel): + dg = self.create_message_stub(self.ai_channel, client_channel) + dg.add_uint16(servermsg.CLIENTAGENT_ADD_SESSION_OBJECT) + dg.add_uint32(do_id) + self.send_datagram(dg) + + def send_CLIENTAGENT_ADD_INTEREST(self, client_channel, interest_id, parent_id, zone_id): + dg = self.create_message_stub(self.ai_channel, client_channel) + dg.add_uint16(servermsg.CLIENTAGENT_ADD_INTEREST) + dg.add_uint16(interest_id) + dg.add_uint32(parent_id) + dg.add_uint32(zone_id) + self.send_datagram(dg) + + def send_STATESERVER_OBJECT_SET_OWNER(self, do_id, owner): + dg = self.create_message_stub(self.ai_channel, do_id) + dg.add_uint16(servermsg.STATESERVER_OBJECT_SET_OWNER) + dg.add_uint64(owner) + self.send_datagram(dg) # Receive messages @@ -352,6 +396,7 @@ def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, sender, recipien def handle_DBSERVER_CREATE_OBJECT_RESP(self, dgi, sender, recipients): context = dgi.read_uint32() do_id = dgi.read_uint32() + print("Received DBSERVER_CREATE_OBJECT_RESP for %d, sender %d, recipients %s" % (do_id, sender, str(recipients))) callback, args, kwargs = self.fire_callback(servermsg.DBSERVER_CREATE_OBJECT_RESP, context) callback(do_id, *args, **kwargs) @@ -373,6 +418,7 @@ def __init__(self, version_string, dcfilename=default_dcfilename): clientmsg.CLIENT_ENTER_OBJECT_REQUIRED_OTHER: self.handle_CLIENT_ENTER_OBJECT_REQUIRED_OTHER, clientmsg.CLIENT_ENTER_OBJECT_REQUIRED_OWNER: self.handle_CLIENT_ENTER_OBJECT_REQUIRED_OWNER, clientmsg.CLIENT_ENTER_OBJECT_REQUIRED_OTHER_OWNER: self.handle_CLIENT_ENTER_OBJECT_REQUIRED_OTHER_OWNER, + clientmsg.CLIENT_ADD_INTEREST : self.handle_CLIENT_ADD_INTEREST, }) def connect(self, connection_success, connection_failure, connection_eject, @@ -541,6 +587,13 @@ def handle_CLIENT_ENTER_OBJECT_REQUIRED_OWNER(self, dgi): def handle_CLIENT_ENTER_OBJECT_REQUIRED_OTHER_OWNER(self, dgi): self.create_view_from_datagram(dgi, cls_postfix = 'OV') + def handle_CLIENT_ADD_INTEREST(self, dgi): + context = dgi.read_uint32() + interest_id = dgi.read_uint16() + parent_id = dgi.read_uint32() + zone_id = dgi.read_uint32() + print("Client received CLIENT_ADD_INTEREST, context %d, interest id %d for (%d, %d)" % (context, interest_id, parent_id, zone_id)) + class InterestInternalRepository(InternalRepository): def __init__(self, *args, **kwargs): InternalRepository.__init__(self, *args, **kwargs) @@ -562,4 +615,4 @@ def add_ai_interest(self, distobj_id, zone_id): def remove_ai_interest(self, context): # FIXME: Implement - pass \ No newline at end of file + pass diff --git a/example/astrond.yml b/example/astrond.yml index 0465db3..057576c 100644 --- a/example/astrond.yml +++ b/example/astrond.yml @@ -39,7 +39,7 @@ roles: - type: database control: 1001 generate: - min: 100000 # Required (no default) + min: 1000000 # Required (no default) max: 4294967295 backend: type: sqlite3 @@ -48,7 +48,7 @@ roles: - type: dbss database: 1001 # The channel of the associated database ranges: - - min: 100000 + - min: 1000000 max: 4294967295 - type: eventlogger diff --git a/example/example_services.py b/example/example_services.py index fd24967..43beafd 100755 --- a/example/example_services.py +++ b/example/example_services.py @@ -5,6 +5,7 @@ # * Turn --login and --ai into something more generic # * Proper logging # * Monitoring output +# * Framerate loop import argparse from time import sleep diff --git a/example/example_views.py b/example/example_views.py index e55f020..80a3935 100644 --- a/example/example_views.py +++ b/example/example_views.py @@ -79,8 +79,16 @@ def init(self): def create_avatar(self, sender, client_id): print("%d called DistributedMaprootAI.create_avatar(%d)" % (sender, client_id)) - self.repo.create_distobj_db('DistributedAvatar', AVATARS_PARENT, AVATARS_ZONE, set_ai = True) - + self.repo.create_distobj_db('DistributedAvatar', AVATARS_PARENT, AVATARS_ZONE, set_ai = True, + creation_callback = self.avatar_created, additional_args = [client_id]) + # FIXME: Choose better interest_id + + def avatar_created(self, do_id, parent_id, zone_id, set_ai, client_id): + print("Avatar was created, now adding interest, setting owner and session object.") + self.repo.send_CLIENTAGENT_ADD_INTEREST(client_id, 666, AVATARS_PARENT, AVATARS_ZONE) + self.repo.send_STATESERVER_OBJECT_SET_OWNER(do_id, client_id) + self.repo.send_CLIENTAGENT_ADD_SESSION_OBJECT(do_id, client_id) + class DistributedMaprootAE(DistributedObject): def init(self): print("DistributedMaprootAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) From b6aacc88bc974fc0a363d321fc7e450f826f1a24 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sun, 9 Nov 2014 00:05:55 +0100 Subject: [PATCH 31/33] Minor cleanup. --- astron/distributed_object.py | 6 +++--- astron/object_repository.py | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 4b879d2..824fdc2 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -52,9 +52,9 @@ def __init__(self, repository, dclass_id, do_id, parent_id, zone_id): } self.required_fields, self.other_fields = separate_fields(self.dclass, ["required"]) # FIXME: Remove after debug - print("Initing %s %d" % (self.dclass.name(), self.do_id)) - print(" REQUIRED fields: %s" % (" ".join([str(idx) for idx in self.required_fields]), )) - print(" OTHER fields: %s" % (" ".join([str(idx) for idx in self.other_fields]), )) + #print("Initing %s %d" % (self.dclass.name(), self.do_id)) + #print(" REQUIRED fields: %s" % (" ".join([str(idx) for idx in self.required_fields]), )) + #print(" OTHER fields: %s" % (" ".join([str(idx) for idx in self.other_fields]), )) # Creating and destroying the view. diff --git a/astron/object_repository.py b/astron/object_repository.py index 381e7af..16c788e 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -437,7 +437,6 @@ def create_message_stub(self): def handle_datagram(self, dg): dgi = DatagramIterator(dg) msgtype = dgi.read_uint16() - print("Handling %d" % (msgtype, )) if msgtype in self.handlers.keys(): self.handlers[msgtype](dgi) else: From 01969a5e8016c9e94b41b6028c3f9ba275af3946 Mon Sep 17 00:00:00 2001 From: Sebastian Hoffmann Date: Sun, 9 Nov 2014 01:46:43 +0100 Subject: [PATCH 32/33] Clean example.db. --- example/example.db | Bin 5120 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/example/example.db b/example/example.db index 0a3c15c8e6bc6026288e7aa1fe524439dcb03eb1..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 GIT binary patch literal 0 HcmV?d00001 literal 5120 zcmeH|K~KUk6vx}XqQiv56C60$iwPtUgIqj1aEZhLI?;r9SPD!s15CGKyz-g2`whJM z5j>iB^1{JwHUv#jJWBeK_W$RD2;Rm?2802>S3urf{$9QGjO^C9t2Jxg;p&? zZyBtmS4@M+Aj`QuR%^6aqZy71(`2Vst*%>bc4D*(Y{Z8SyVR}fv2Nwc`}uiVArPJ) z?ZGO|rfKMn`Ja4|Ze;WrgcJ&Gupi&e8MPNM$Y(>XV{l6ZUsZOB? z{E Date: Tue, 11 Nov 2014 01:48:25 +0100 Subject: [PATCH 33/33] First lines of internal interests. Major overhaul of views and DO structure. Some other changes. --- astron/distributed_object.py | 32 +++++- astron/object_repository.py | 131 +++++++++++++++------ example/astrond.yml | 2 +- example/example.dc | 32 ++++-- example/example_client.py | 6 +- example/example_services.py | 78 ++++++++----- example/example_views.py | 216 ++++++++++++++++++++++++----------- example/shared_constants.py | 24 ++-- 8 files changed, 361 insertions(+), 160 deletions(-) diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 824fdc2..90f9c82 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -67,10 +67,6 @@ def delete(self): # FIXME: Redup in object_repository if the docstring is actually accurate. print("DO deleted: %d" % (self.do_id, )) - def acquire_ai(self): - # FIXME: This should have more intelligence, i.e. using GET_AI (CHANGE_AI?) - self.repo.send_STATESERVER_OBJECT_SET_AI(self.do_id) - def update_field(self, sender, field_id, dgi): """Handles incoming SET_FIELD updates.""" decoded_args = [] @@ -212,6 +208,34 @@ def unpack_char(self, dgi): def unpack_string(self, dgi): return dgi.read_string() + # Server-side things + + def acquire_ai(self): + # FIXME: This should have more intelligence, i.e. using GET_AI (CHANGE_AI?) + self.repo.send_STATESERVER_OBJECT_SET_AI(self.do_id) + + def add_ai_interest(self, distobj_id, zone_id): + self.repo.add_ai_interest(distobj_id, zone_id, by_distobj = self.do_id) + + def remove_ai_interest(self, distobj_id, zone_id): + self.repo.remove_ai_interest(distobj_id, zone_id, by_distobj = self.do_id) + + def interest_distobj_enter(self, view, do_id, parent_id, zone_id): + """Overwrite this to be notified of new distributed objects + entering a location that this object is interested in.""" + print("WARNING: Un-overwritten interest_distobj_enter called in %d" % (self.do_id, )) + + def interest_distobj_ai_enter(self, view, do_id, parent_id, zone_id): + """Overwrite this to be notified of new AI distributed objects + entering a location that this object is interested in.""" + print("WARNING: Un-overwritten interest_distobj_ai_enter called in %d" % (self.do_id, )) + + def interest_changing_location_enter(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): + print("WARNING: Un-overwritten interest_changing_location_enter called in %d" % (self.do_id, )) + + def interest_changing_location_leave(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): + print("WARNING: Un-overwritten interest_changing_location_leave called in %d" % (self.do_id, )) + # Sending def send_CLIENTAGENT_EJECT(self, client_id, disconnect_code, reason): diff --git a/astron/object_repository.py b/astron/object_repository.py index 16c788e..8ce44de 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -161,15 +161,20 @@ def handle_datagram(self, dg): def create_view_from_datagram(self, dgi, cls_postfix = ''): do_id = dgi.read_uint32() - parent_id = dgi.read_uint32() - zone_id = dgi.read_uint32() - dclass_id = dgi.read_uint16() - # Create the view object - cls = self.dclass_id_to_cls[(dclass_id, cls_postfix)] - dist_obj = cls(self, dclass_id, do_id, parent_id, zone_id) - self.distributed_objects[do_id] = dist_obj - # FIXME: Read the field values from the dgi and apply them - dist_obj.init() + # Only create a view if one doesn't already exist! + if not (do_id in self.distributed_objects.keys()): + parent_id = dgi.read_uint32() + zone_id = dgi.read_uint32() + dclass_id = dgi.read_uint16() + # Create the view object + cls = self.dclass_id_to_cls[(dclass_id, cls_postfix)] + dist_obj = cls(self, dclass_id, do_id, parent_id, zone_id) + self.distributed_objects[do_id] = dist_obj + # FIXME: Read the field values from the dgi and apply them + dist_obj.init() + return dist_obj, do_id, parent_id, zone_id + else: + return False def create_distobjglobal_view(self, cls_name, do_id, set_ai = False): cls = self.dclass_name_to_cls[cls_name] @@ -361,6 +366,14 @@ def send_STATESERVER_OBJECT_SET_OWNER(self, do_id, owner): dg.add_uint64(owner) self.send_datagram(dg) + def send_STATESERVER_OBJECT_GET_ZONE_OBJECTS(self, context, parent_id, zone_id): + dg = self.create_message_stub(self.ai_channel, parent_id) + dg.add_uint16(servermsg.STATESERVER_OBJECT_GET_ZONE_OBJECTS) + dg.add_uint32(context) + dg.add_uint32(parent_id) + dg.add_uint32(zone_id) + self.send_datagram(dg) + # Receive messages def handle_STATESERVER_OBJECT_SET_FIELD(self, dgi, sender, recipients): @@ -375,10 +388,7 @@ def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, dgi, sender, recipients): new_zone = dgi.read_uint32() old_parent = dgi.read_uint32() old_zone = dgi.read_uint32() - for recipient in recipients: - if recipient in self.distributed_objects.keys(): - self.distributed_objects[recipient].handle_STATESERVER_OBJECT_CHANGING_LOCATION(sender, do_id, new_parent, new_zone, old_parent, old_zone) - # FIXME: If the repo has "interest" in either location, that should be handled somehow. + # FIXME: Do nothing else. def handle_STATESERVER_OBJECT_GET_AI(self, dgi, sender, recipients): print("handle_STATESERVER_OBJECT_GET_AI", sender, recipients) @@ -390,7 +400,6 @@ def handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED(self, dgi, sender, re self.create_view_from_datagram(dgi, cls_postfix = 'AE') def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, sender, recipients): - print("handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED", sender, recipients) self.create_view_from_datagram(dgi, cls_postfix = 'AI') def handle_DBSERVER_CREATE_OBJECT_RESP(self, dgi, sender, recipients): @@ -400,6 +409,77 @@ def handle_DBSERVER_CREATE_OBJECT_RESP(self, dgi, sender, recipients): callback, args, kwargs = self.fire_callback(servermsg.DBSERVER_CREATE_OBJECT_RESP, context) callback(do_id, *args, **kwargs) +class InterestInternalRepository(InternalRepository): + def __init__(self, *args, **kwargs): + InternalRepository.__init__(self, *args, **kwargs) + self.repo_interests = set() + self.distobj_interests_do_id_to_locations = {} + self.distobj_interests_location_to_do_id = {} + + def add_ai_interest(self, distobj_id, zone_id, by_distobj = False): + if by_distobj: + print("Interest for %d in (%d, %d)" % (by_distobj, distobj_id, zone_id)) + if not (by_distobj in self.distobj_interests_do_id_to_locations.keys()): + self.distobj_interests_do_id_to_locations[by_distobj] = [parent_zone_to_location(distobj_id, zone_id)] + else: + self.distobj_interests_do_id_to_locations[by_distobj].append(parent_zone_to_location(distobj_id, zone_id)) + if not (by_distobj in self.distobj_interests_location_to_do_id.keys()): + self.distobj_interests_location_to_do_id[parent_zone_to_location(distobj_id, zone_id)] = [by_distobj] + else: + self.distobj_interests_location_to_do_id[parent_zone_to_location(distobj_id, zone_id)].append(by_distobj) + else: + print("Interest for repo in (%d, %d)" % (distobj_id, zone_id)) + self.repo_interests.add(parent_zone_to_location(distobj_id, zone_id)) + self.send_CONTROL_ADD_CHANNEL(parent_zone_to_location(distobj_id, zone_id)) + # Request list of objects already existing in that zone for ENTER + # FIXME: Can we do something with the context? + print("repo: STATESERVER_OBJECT_GET_ZONE_OBJECTS(%d, %d)" % (distobj_id, zone_id)) + self.send_STATESERVER_OBJECT_GET_ZONE_OBJECTS(0, distobj_id, zone_id) + # FIXME: Messages for DOs that haven't entered yet may come + # over the control channel. Either some kind of solution is + # needed, or AIR interests shall be implemented in Astron as + # actual messages. + + def remove_ai_interest(self, distobj_id, zone_id, by_distobj = False): + # FIXME: Implement + pass + + # Overwrites + # return dist_obj, do_id, parent_id, zone_id + def handle_STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED(self, dgi, sender, recipients): + new_distobj = self.create_view_from_datagram(dgi, cls_postfix = 'AE') + if new_distobj: + view, do_id, parent_id, zone_id = new_distobj + if parent_zone_to_location(parent_id, zone_id) in self.distobj_interests_location_to_do_id.keys(): + interested_distobjs = self.distobj_interests_location_to_do_id[parent_zone_to_location(parent_id, zone_id)] + for distobj in interested_distobjs: + self.distributed_objects[distobj].interest_distobj_enter(view, do_id, parent_id, zone_id) + + def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, sender, recipients): + new_distobj = self.create_view_from_datagram(dgi, cls_postfix = 'AI') + if new_distobj: + view, do_id, parent_id, zone_id = new_distobj + if parent_zone_to_location(parent_id, zone_id) in self.distobj_interests_location_to_do_id.keys(): + interested_distobjs = self.distobj_interests_location_to_do_id[parent_zone_to_location(parent_id, zone_id)] + for distobj in interested_distobjs: + self.distributed_objects[distobj].interest_distobj_ai_enter(view, do_id, parent_id, zone_id) + + def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, dgi, sender, recipients): + print("handle_STATESERVER_OBJECT_CHANGING_LOCATION", sender, recipients) + do_id = dgi.read_uint32() + new_parent = dgi.read_uint32() + new_zone = dgi.read_uint32() + old_parent = dgi.read_uint32() + old_zone = dgi.read_uint32() + if parent_zone_to_location(new_parent, new_zone) in self.distobj_interests_location_to_do_id.keys(): + interested_distobjs = self.distobj_interests_location_to_do_id[parent_zone_to_location(new_parent, new_zone)] + for distobj in interested_distobjs: + self.distributed_objects[distobj].interest_changing_location_enter(sender, do_id, new_parent, new_zone, old_parent, old_zone) + if parent_zone_to_location(old_parent, old_zone) in self.distobj_interests_location_to_do_id.keys(): + interested_distobjs = self.distobj_interests_location_to_do_id[parent_zone_to_location(old_parent, old_zone)] + for distobj in interested_distobjs: + self.distributed_objects[distobj].interest_changing_location_leave(sender, do_id, new_parent, new_zone, old_parent, old_zone) + class ClientRepository(ObjectRepository): def __init__(self, version_string, dcfilename=default_dcfilename): ObjectRepository.__init__(self, dcfilename=dcfilename) @@ -592,26 +672,3 @@ def handle_CLIENT_ADD_INTEREST(self, dgi): parent_id = dgi.read_uint32() zone_id = dgi.read_uint32() print("Client received CLIENT_ADD_INTEREST, context %d, interest id %d for (%d, %d)" % (context, interest_id, parent_id, zone_id)) - -class InterestInternalRepository(InternalRepository): - def __init__(self, *args, **kwargs): - InternalRepository.__init__(self, *args, **kwargs) - self.repo_interests = set() - - def add_ai_interest(self, distobj_id, zone_id): - self.repo_interests.add(parent_zone_to_location(distobj_id, zone_id)) - # FIXME: As do_ids and zones may be of different sizes, - # this calculation has to take that into account. - self.send_CONTROL_ADD_CHANNEL(parent_zone_to_location(distobj_id, zone_id)) - # FIXME: Request list of objects already existing in that - # zone for ENTER. - # self.send_STATESERVER_OBJECT_GET_ZONE_OBJECTS(context, distobj_id, zone_id) - # FIXME: Messages for DOs that haven't entered yet may come - # over the control channel. Either some kind of solution is - # needed, or AIR interests shall be implemented in Astron as - # actual messages. - # FIXME: There should also be remove_ai_interest(distobj, zone) - - def remove_ai_interest(self, context): - # FIXME: Implement - pass diff --git a/example/astrond.yml b/example/astrond.yml index 057576c..aab7265 100644 --- a/example/astrond.yml +++ b/example/astrond.yml @@ -10,7 +10,7 @@ general: # Actually just DOGs, not *the* UberDOG. uberdogs: - id: 20000 - class: LoginManager + class: PointOfContact anonymous: true # May be contacted by status New clients to be Established messagedirector: diff --git a/example/example.dc b/example/example.dc index 0f70904..0993e75 100644 --- a/example/example.dc +++ b/example/example.dc @@ -4,26 +4,42 @@ typedef uint32 zoneId; typedef uint64 channel; // The Python Views for these distributed classes. -from example_views import LoginManager/AI/UD -from example_views import DistributedMaproot/AI/UD/AE -from example_views import DistributedAvatar/AI/OV +from example_views import PointOfContact/UD +from example_views import GameRoot/AI/AE +from example_views import LoginService/AI/AE +from example_views import World/AI/AE +from example_views import AIServer/AI/AE +from example_views import Avatar/AI/AE/OV // A simple DOG for username/password authentication and handoff to // the DistributedMaproot for avatar creation. -dclass LoginManager { - login(string username, string password) clsend; +dclass PointOfContact { + login(string username, string password) clsend airecv; }; -// The root object of the map, container for the DistributedAvatars. -dclass DistributedMaproot { +// The root of the visibility tree, a container for services and +// top-level stuff. +dclass GameRoot {}; + +// The user authentication service. +dclass LoginService { + login(channel client, string username, string password) airecv; +} + +// FIXME: Comment +dclass World { create_avatar(channel client) airecv; }; +// The root object of the map, container for the DistributedAvatars. +dclass AIServer { +}; + // The actual class for avatar control. // The idea is that a Client can set its intention for its heading // and speed, but only the controlling AI can set its actual // position and heading. -dclass DistributedAvatar { +dclass Avatar { setXYZH(int16 / 1000, int16 / 1000, int16 / 1000, int16 / 50) broadcast required; indicateIntent(int16 / 10, int16 / 10) ownsend airecv; }; diff --git a/example/example_client.py b/example/example_client.py index ccb469f..8176198 100755 --- a/example/example_client.py +++ b/example/example_client.py @@ -3,15 +3,15 @@ from time import sleep from astron.object_repository import ClientRepository -from shared_constants import LOGIN_MANAGER_DO_ID +from shared_constants import POINT_OF_CONTACT_DO_ID if __name__ == '__main__': repo = ClientRepository('SimpleExample v0.2', 'example.dc') def connected(): print('Connection established.') - login_manager = repo.create_distobjglobal_view('LoginManager', LOGIN_MANAGER_DO_ID) - login_manager.login("guest", "guest") + poc = repo.create_distobjglobal_view('PointOfContact', POINT_OF_CONTACT_DO_ID) + poc.login("guest", "guest") def ejected(error_code, reason): print('Got ejected (%i): %s' % (error_code, reason)) diff --git a/example/example_services.py b/example/example_services.py index 43beafd..da7c716 100755 --- a/example/example_services.py +++ b/example/example_services.py @@ -12,9 +12,8 @@ import datetime from astron.object_repository import InterestInternalRepository as InternalRepository -from shared_constants import LOGIN_MANAGER_DO_ID, \ - MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, \ - SERVICES_CHANNEL, STATESERVER, DBSS, \ +from shared_constants import SERVICES_CHANNEL, STATESERVER, DBSS, \ + POINT_OF_CONTACT_DO_ID, GAME_ROOT_DO_ID, WORLD_ZONE, LOGIN_SERVICE_ZONE, AI_SERVICES_ZONE, \ DC_FILE, \ SERVER_FRAMERATE @@ -26,14 +25,10 @@ def __init__(self, ai_channel = SERVICES_CHANNEL, host = '127.0.0.1', port = 7199, - frame_time = 1./100., - login = False, - ai = False): + frame_time = 1./100.): self.host = host self.port = port self.frame_time = frame_time - self.login = login - self.ai = ai self.repo = InternalRepository(dc_file, stateserver = stateserver, dbss = dbss, @@ -47,20 +42,42 @@ def start(self): # FIXM: Log ratio of time left, prevalence of overlong frames, total accumulated lag sleep(0.1) + def connected(self): + print('Connection established, connected() not overridden.') + + def failed(self): + print('Connection attempt failed, failed() not overridden.') + +class ExampleServer(AstronServer): + def __init__(self, + contact = False, root = False, world = False, login = False, ai = False, + *args, **kwargs): + AstronServer.__init__(self, *args, **kwargs) + self.contact = contact + self.root = root + self.world = world + self.login = login + self.ai = ai + def connected(self): print('Connection established.') - # Login server, assigner of AIs + # Point of contact for newly connected clients (state New) + if self.contact: + print("Creating Point of Contact") + self.repo.create_distobjglobal_view('PointOfContactUD', POINT_OF_CONTACT_DO_ID, set_ai = True) + self.repo.add_ai_interest(GAME_ROOT_DO_ID, LOGIN_SERVICE_ZONE) + if self.root: + print("Creating GameRoot") + self.repo.create_distobj('GameRoot', GAME_ROOT_DO_ID, 0, 0, set_ai = True) + if self.world: + print("Creating World") + self.repo.create_distobj_db('World', GAME_ROOT_DO_ID, WORLD_ZONE, set_ai = True) if self.login: print("Starting Login service") - self.repo.create_distobjglobal_view('LoginManagerUD', LOGIN_MANAGER_DO_ID, set_ai = True) - self.repo.add_ai_interest(MAP_ROOT_PARENT, MAP_ROOT_ZONE) - # AI server + self.repo.create_distobj_db('LoginService', GAME_ROOT_DO_ID, LOGIN_SERVICE_ZONE, set_ai = True) if self.ai: print("Starting AI service") - self.repo.create_distobj('DistributedMaproot', MAP_ROOT_DO_ID, MAP_ROOT_PARENT, MAP_ROOT_ZONE, set_ai = True) - - def failed(self): - print('Connection attempt failed.') + self.repo.create_distobj_db('AIServer', GAME_ROOT_DO_ID, AI_SERVICES_ZONE, set_ai = True) if __name__ == '__main__': # FIXME: Add an epilog, at least an example usage @@ -78,25 +95,34 @@ def failed(self): help='Number of cycles per second to aim for') parser.add_argument('-d', '--dbss', type = int, default = DBSS, help='Number of cycles per second to aim for') - parser.add_argument('-r', '--framerate', type = float, default = SERVER_FRAMERATE, + parser.add_argument('-f', '--framerate', type = float, default = SERVER_FRAMERATE, help='Number of cycles per second to aim for') # FIXME: These are specific to this application. Considering how # generic they are, they *should* be convertible into more # generic arguments. Maybe these are the positional args? + parser.add_argument('-p', '--point-of-contact', action = "store_true", + help='PointOfContact DOG') + parser.add_argument('-r', '--root', action = "store_true", + help='GameRoot object') + parser.add_argument('-w', '--world', action = "store_true", + help='World object') parser.add_argument('-l', '--login', action = "store_true", help='Login service') parser.add_argument('-a', '--ai', action = "store_true", help='AI service') args = parser.parse_args() - server = AstronServer(dc_file = args.dcfile, - stateserver = STATESERVER, - dbss = DBSS, - ai_channel = args.channel, - host = args.host, - port = args.port, - frame_time = 1. / args.framerate, - login = args.login, - ai = args.ai) + server = ExampleServer(dc_file = args.dcfile, + stateserver = STATESERVER, + dbss = DBSS, + ai_channel = args.channel, + host = args.host, + port = args.port, + frame_time = 1. / args.framerate, + contact = args.point_of_contact, + root = args.root, + world = args.world, + login = args.login, + ai = args.ai) server.start() diff --git a/example/example_views.py b/example/example_views.py index 80a3935..cffabfb 100644 --- a/example/example_views.py +++ b/example/example_views.py @@ -1,7 +1,7 @@ from datetime import datetime from astron.object_repository import DistributedObject -from shared_constants import LOGIN_MANAGER_DO_ID, MAP_ROOT_ZONE, AVATARS_PARENT, AVATARS_ZONE +from shared_constants import LOGIN_SERVICE_ZONE, WORLD_ZONE, GAME_ROOT_DO_ID, AI_SERVICES_ZONE import random from pprint import pprint @@ -12,110 +12,194 @@ # ------------------------------------------------------------------- -# LoginManager -# * Registers a DistributedMaproot -# * Authenticates Clients -# * Makes DistributedMaproot create an avatar for new Clients. +# PointOfContact +# * Is the only DOG, and is the only distobj that a player can +# contact before logging in. +# * Has interest in LoginServices +# * Redirects player logins to a LoginService, if possible. # ------------------------------------------------------------------- -class LoginManager(DistributedObject): +class PointOfContact(DistributedObject): def init(self): - print("LoginManager view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + print("PointOfContact view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) def login(self, username, password): print("Client logging in") self.send_update("login", username, password) -class LoginManagerAI(DistributedObject): - def init(self): - print("LoginManagerAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - -class LoginManagerUD(DistributedObject): +class PointOfContactUD(DistributedObject): def init(self): - self.maproot_distobjs = set() - print("LoginManagerUD view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + self.add_ai_interest(GAME_ROOT_DO_ID, LOGIN_SERVICE_ZONE) + self.login_services = {} + print("PointOfContactUD view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) def login(self, sender, username, password): print("Received login request for %d" % (sender, )) - if len(self.maproot_distobjs) > 0: - if username == "guest" and password == "guest": - # Login successful - self.repo.send_CLIENTAGENT_SET_STATE(sender, 2, sender = self.do_id) - print(" Logging in successfully") - maproot_for_client = random.choice(list(self.maproot_distobjs)) - self.repo.distobj_by_do_id(maproot_for_client).create_avatar(sender, sender) - else: - # Bad credentials - self.send_CLIENTAGENT_EJECT(sender, 122, "Bad credentials") - print(" Disconnecting for bad credentials") + if len(self.login_services.keys()) > 0: + view = random.choice(self.login_services.values()) + view.login(sender, username, password) else: - # No maproot has appeared yet. - # FIXME: ...or has left, and no replacement has arrived. - self.send_CLIENTAGENT_EJECT(sender, 999, "Server isn't ready") - print("Dropping connection attempt due to missing maproot") + # No login service is known. + self.send_CLIENTAGENT_EJECT(sender, 999, "Server isn't ready for logins") + print(" Dropping connection attempt due to missing LoginService") - def handle_STATESERVER_OBJECT_CHANGING_LOCATION(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): - if (new_parent == LOGIN_MANAGER_DO_ID) and (new_zone == MAP_ROOT_ZONE): + def interest_distobj_enter(self, view, do_id, parent_id, zone_id): + print(" PointOfContactUD learned of new LoginService %d" % (do_id, )) + if (parent_id == GAME_ROOT_DO_ID) and (zone_id == LOGIN_SERVICE_ZONE): + self.login_services[do_id] = view + + def interest_changing_location_enter(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): + if (new_parent == GAME_ROOT_DO_ID) and (new_zone == LOGIN_SERVICE_ZONE): # A new maproot "service" has entered - self.maproot_distobjs.add(do_id) - print("LoginManagerUD added %d to maproot services." % (do_id, )) - elif (old_parent == LOGIN_MANAGER_DO_ID) and (old_zone == MAP_ROOT_ZONE): + self.login_services.add(do_id) + print(" PointOfContactUD added %d to maproot services." % (do_id, )) + + def interest_changing_location_leave(self, sender, do_id, new_parent, new_zone, old_parent, old_zone): + if (old_parent == GAME_ROOT_DO_ID) and (old_zone == LOGIN_SERVICE_ZONE): # A maproot has just left - self.maproot_distobjs.remove(do_id) - print("LoginManagerUD removed %d from maproot services." % (do_id, )) + self.login_services.remove(do_id) + print(" PointOfContactUD removed %d from maproot services." % (do_id, )) # ------------------------------------------------------------------- -# DistributedMaproot +# GameRoot +# * Is a container for top-level objects, especially the world and +# services. +# ------------------------------------------------------------------- + +class GameRoot(DistributedObject): + pass + +class GameRootAI(DistributedObject): + pass + +class GameRootAE(DistributedObject): + pass + +# ------------------------------------------------------------------- +# LoginService +# * Registers a CharacterServer +# * Authenticates Clients +# * Makes CharacterServer create an avatar for new Clients. +# ------------------------------------------------------------------- + +# This one isn't used on the client. +class LoginService(DistributedObject): + def init(self): + print("LoginService view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + +class LoginServiceAE(DistributedObject): + def init(self): + print("LoginServiceAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + + def login(self, client_channel, username, password): + print(" LoginServiceAE %d received login request for %d" % (self.do_id, client_channel, )) + self.send_update('login', client_channel, username, password) + +class LoginServiceAI(DistributedObject): + def init(self): + self.add_ai_interest(GAME_ROOT_DO_ID, WORLD_ZONE) + self.worlds = {} + print("LoginServiceAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + + def login(self, sender, client_channel, username, password): + print(" LoginServiceAI %d received login request for %d" % (self.do_id, client_channel, )) + if username == "guest" and password == "guest": + # Login successful + self.repo.send_CLIENTAGENT_SET_STATE(client_channel, 2, sender = self.do_id) + print(" Logging in successfully") + # FIXME: Create Avatar + else: + # Bad credentials + self.send_CLIENTAGENT_EJECT(client_channel, 122, "Bad credentials") + print(" Disconnecting for bad credentials") + + def interest_distobj_enter(self, view, do_id, parent_id, zone_id): + if (parent_id == GAME_ROOT_DO_ID) and (zone_id == WORLD_ZONE): + print(" LoginServiceAI learned of new World %d" % (do_id, )) + self.worlds[do_id] = view + +# ------------------------------------------------------------------- +# World +# * is a container for Avatars (so far) +# ------------------------------------------------------------------- + +class World(DistributedObject): + pass + +class WorldAI(DistributedObject): + def init(self): + self.add_ai_interest(GAME_ROOT_DO_ID, AI_SERVICES_ZONE) + self.ai_services = {} + print("WorldAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + + def create_avatar(self, sender, client): + print(" not implemented: WorldAI %d should create avatar for %d" % (self.do_id, client)) + + def interest_distobj_enter(self, view, do_id, parent_id, zone_id): + if (parent_id == GAME_ROOT_DO_ID) and (zone_id == AI_SERVICES_ZONE): + print(" LoginServiceAI learned of new AIServer %d" % (do_id, )) + self.ai_services[do_id] = view + +class WorldAE(DistributedObject): + def init(self): + print("WorldAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + + def create_avatar(self, client): + self.send_update('create_avatar', client) + +# ------------------------------------------------------------------- +# CharacterServer # * has all avatars in its zone 0 # * generates new avatars # ------------------------------------------------------------------- -class DistributedMaproot(DistributedObject): +class AIServer(DistributedObject): pass -class DistributedMaprootAI(DistributedObject): +class AIServerAI(DistributedObject): def init(self): - print("DistributedMaprootAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - - def create_avatar(self, sender, client_id): - print("%d called DistributedMaprootAI.create_avatar(%d)" % (sender, client_id)) - self.repo.create_distobj_db('DistributedAvatar', AVATARS_PARENT, AVATARS_ZONE, set_ai = True, - creation_callback = self.avatar_created, additional_args = [client_id]) - # FIXME: Choose better interest_id - - def avatar_created(self, do_id, parent_id, zone_id, set_ai, client_id): - print("Avatar was created, now adding interest, setting owner and session object.") - self.repo.send_CLIENTAGENT_ADD_INTEREST(client_id, 666, AVATARS_PARENT, AVATARS_ZONE) - self.repo.send_STATESERVER_OBJECT_SET_OWNER(do_id, client_id) - self.repo.send_CLIENTAGENT_ADD_SESSION_OBJECT(do_id, client_id) + print("AIServerAI view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + # self.repo.add_ai_interest(WORLD_PARENT, WORLD_ZONE) + + #def create_avatar(self, sender, client_id): + # print("%d called CharacterServerAI.create_avatar(%d)" % (sender, client_id)) + # self.repo.create_distobj_db('Avatar', AVATARS_PARENT, AVATARS_ZONE, set_ai = True, + # creation_callback = self.avatar_created, additional_args = [client_id]) + # # FIXME: Choose better interest_id + # + #def avatar_created(self, do_id, parent_id, zone_id, set_ai, client_id): + # print("Avatar was created, now adding interest, setting owner and session object.") + # self.repo.send_CLIENTAGENT_ADD_INTEREST(client_id, 666, AVATARS_PARENT, AVATARS_ZONE) + # self.repo.send_STATESERVER_OBJECT_SET_OWNER(do_id, client_id) + # self.repo.send_CLIENTAGENT_ADD_SESSION_OBJECT(do_id, client_id) -class DistributedMaprootAE(DistributedObject): +class AIServerAE(DistributedObject): def init(self): - print("DistributedMaprootAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + print("AIServerAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) def create_avatar(self, sender, client_id): - print("DistributedMaprootAE.create_avatar(sender %d, client_id %d)" % (sender, client_id)) + print(" AIServerAE.create_avatar(sender %d, client_id %d)" % (sender, client_id)) self.send_update('create_avatar', client_id) -class DistributedMaprootUD(DistributedObject): - def init(self): - print("DistributedMaprootUD view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) - # ------------------------------------------------------------------- -# DistributedAvatar +# Avatar # * represents players in the scene graph # * routes indications of movement intents to AI # * updates the actual position and orientation # ------------------------------------------------------------------- -class DistributedAvatar(DistributedObject): +class Avatar(DistributedObject): + def init(self): + print("Avatar created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + +class AvatarAI(DistributedObject): def init(self): - print("DistributedAvatar created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + print("AvatarAI created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) -class DistributedAvatarAI(DistributedObject): +class AvatarAE(DistributedObject): def init(self): - print("DistributedAvatarAI created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + print("AvatarAE created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) -class DistributedAvatarOV(DistributedObject): +class AvatarOV(DistributedObject): def init(self): - print("DistributedAvatarOV created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + print("AvatarOV created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) diff --git a/example/shared_constants.py b/example/shared_constants.py index ff17d50..5856c11 100644 --- a/example/shared_constants.py +++ b/example/shared_constants.py @@ -11,23 +11,17 @@ # 10,000 - 19,999: Internal Repositories SERVICES_CHANNEL = 10000 -WORLD = 10001 # 20,000 - 99,999: Fixed-ID Distributed Objects in StateServer -LOGIN_MANAGER_DO_ID = 20000 -# The increasingly inaccurately named MapRoot is the representative -# Distributed Object for the repository that AIs for player -# characters. -# FIXME: These need more flexible assignment, so that several -# InternalRepos can share a pool of DO IDs. -MAP_ROOT_DO_ID = 21000 -MAP_ROOT_PARENT = LOGIN_MANAGER_DO_ID -MAP_ROOT_ZONE = 0 -MAP_ROOT_LOCATION = parent_zone_to_location(MAP_ROOT_PARENT, MAP_ROOT_ZONE) +POINT_OF_CONTACT_DO_ID = 20000 -# 100,000- 999,999:Clients +GAME_ROOT_DO_ID = 30000 +GAME_ROOT_PARENT = 0 +GAME_ROOT_ZONE = 0 +LOGIN_SERVICE_ZONE = 0 +WORLD_ZONE = 1 +AI_SERVICES_ZONE = 2 + +# 100,000- 999,999: Clients # 100,000 - 4294967295: Distributed Objects in DBSS -AVATARS_PARENT = LOGIN_MANAGER_DO_ID -AVATARS_ZONE = 1 -AVATARS_LOCATION = parent_zone_to_location(LOGIN_MANAGER_DO_ID, AVATARS_ZONE)