diff --git a/.gitignore b/.gitignore index 48c58e1..3e9461e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ .project .pydevproject .gitignore +*.log* +*.db 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. diff --git a/astron/connection.py b/astron/connection.py index ccc6a72..97042fd 100644 --- a/astron/connection.py +++ b/astron/connection.py @@ -1,3 +1,4 @@ +import errno import struct import socket from bamboo.wire import Datagram @@ -12,9 +13,10 @@ 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) self._is_connected = True self.reading_message = False self.remaining_length = DATAGRAM_HEADER_SIZE @@ -22,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 @@ -47,11 +50,11 @@ def poll_datagram(self): # block above finished reading a message body, then this # happens: if self.reading_message and (self.remaining_length == 0): - #self.partial_data = '' # FIXME: Length header now has do be part of the datagram, too? - self.remaining_length = DATAGRAM_HEADER_SIZE - self.reading_message = False dg = Datagram() dg.add_data(self.partial_data) + self.partial_data = '' + self.remaining_length = DATAGRAM_HEADER_SIZE + self.reading_message = False return dg # So we did not actually finish reading a message at all. :( return diff --git a/astron/distributed_object.py b/astron/distributed_object.py index 81d6d2c..90f9c82 100644 --- a/astron/distributed_object.py +++ b/astron/distributed_object.py @@ -1,16 +1,256 @@ +# 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, 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.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 + self.type_packer = {module.kTypeInt8: self.pack_int8, + 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, + module.kTypeString: self.pack_string, + module.kTypeVarstring: self.pack_string, + } + 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, + } + 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): - print("DO created: %d" % (self.do_id, )) + """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 send_update(self, field_name, value): - # FIXME: Find field type, write datagram, send + def update_field(self, sender, field_id, dgi): + """Handles incoming SET_FIELD updates.""" + decoded_args = [] + 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) + 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("Updating field %s in %d with args %s" % (field.name(), self.do_id, str(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): + print("Distributed method %s requires %d args, %d were provided" % (field_name, num_args, len(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(self.do_id, self.do_id) + dg.add_int16(servermsg.STATESERVER_OBJECT_SET_FIELD) + dg.add_int32(self.do_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]) + else: + 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): + 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 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) + + def pack_int16(self, dg, value): + dg.add_int16(value) + + def pack_int32(self, dg, 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): + 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) + + 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() + + # 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): + 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): + """Override this to react to STATESERVER_OBJECT_CHANGING_LOCATION messages.""" pass diff --git a/astron/helpers.py b/astron/helpers.py new file mode 100644 index 0000000..506c8c5 --- /dev/null +++ b/astron/helpers.py @@ -0,0 +1,46 @@ +# 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 << 32) | 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/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 5dd7b58..8ce44de 100644 --- a/astron/object_repository.py +++ b/astron/object_repository.py @@ -6,20 +6,24 @@ from connection import Connection import client_messages as clientmsg import internal_messages as servermsg -from distributed_object import DistributedObject -import socket +from helpers import parent_zone_to_location, separate_fields import importlib -from pprint import pprint DATAGRAM_SIZE = 2 DATAGRAM_ENCODING = ', '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 - dc_module = self.mod.get_import(i_id).module - for symbol in self.mod.get_import(i_id).symbols: + 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 = symbol.split('/') + fragments = str(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 + #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 - pprint(self.dclass_id_to_cls) - pprint(self.dclass_name_to_cls) + self.dclass_name_to_cls[(base_class, postfix)] = cls - - self.handlers = {} - - # FIXME: Maybe move this into ClientRepository, if Internals won't get Interests in the future. - self.interest_counters = {} - self.interest_callback_map = {} + def distobj_by_do_id(self, do_id): + try: + return self.distributed_objects[do_id] + except KeyError: + print("KeyError: No view for do_id %d present." % (do_id, )) def poll_till_empty(self): """Process all received messages. @@ -80,7 +142,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.""" @@ -93,51 +154,337 @@ def poll_forever(self): return def handle_datagram(self, dg): - dgi = DatagramIterator(dg) - msgtype = dgi.read_uint16() - if msgtype in self.handlers.keys(): - self.handlers[msgtype](dgi) - else: - print("Received unhandled message type " + str(msgtype)) + 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() - zone_id = dgi.read_uint32() - dclass_id = dgi.read_uint16() - # 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) - 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_view_by_classname(self, cls_name, do_id, parent_id, zone_id): - cls = DistributedObject - dist_obj = cls(self, do_id, parent_id, zone_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 - # FIXME: Read the field values from the dgi and apply them 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 + + 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): + def __init__(self, dcfilename=default_dcfilename, stateserver = 400000, dbss = 400001, ai_channel=500000): ObjectRepository.__init__(self, dcfilename=dcfilename) - self.handlers = {} - - def connect(self, host=default_host, port=default_internal_port): + self.stateserver = stateserver + self.dbss = dbss + 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_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.DBSERVER_CREATE_OBJECT_RESP : self.handle_DBSERVER_CREATE_OBJECT_RESP, + # FIXME: Add handlers for incoming messages + }) + self.global_views = {} + + 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.ai_channel) + connection_success() + + def handle_datagram(self, dg): + dgi = DatagramIterator(dg) + num_recipients = dgi.read_uint8() + recipients = [dgi.read_uint64() for _ in range(0, num_recipients)] + sender = dgi.read_uint64() + msgtype = dgi.read_uint16() + if msgtype in self.handlers.keys(): + self.handlers[msgtype](dgi, sender, recipients) + 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, creation_callback = False, additional_args = []): + dclass_id = self.dclass_name_to_id[cls_name] + 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_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 + + 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(channel) + self.send_datagram(dg) + + def send_STATESERVER_OBJECT_SET_AI(self, do_id): + dg = self.create_message_stub(self.ai_channel, 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_CREATE_OBJECT_WITH_REQUIRED) + 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.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) + dg.add_uint32(self.zone) + dg.add_uint16(self.dclass_id) + # FIXME: Add REQUIRED fields + # 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: 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 + dg = self.create_message_stub(sender, clientagent) + 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) + + 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): + do_id = dgi.read_uint32() + field_id = dgi.read_uint16() + 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() + # FIXME: Do nothing else. + + 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): + self.create_view_from_datagram(dgi, cls_postfix = 'AE') + + def handle_STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED(self, dgi, 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() + 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) + +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) self.version_string = version_string - self.distributed_objects = {} - self.owner_views = {} + self.msg_type = MSG_TYPE_CLIENT self.handlers.update({ clientmsg.CLIENT_HELLO_RESP: self.handle_CLIENT_HELLO_RESP, clientmsg.CLIENT_EJECT: self.handle_CLIENT_EJECT, @@ -151,6 +498,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, @@ -160,8 +508,19 @@ def connect(self, connection_success, connection_failure, connection_eject, self.connection_eject = connection_eject ObjectRepository.connect(self, host, port) - # FIXME: send_client_hello needs to be asynchronous. self.send_CLIENT_HELLO() + + def create_message_stub(self): + dg = Datagram() + return dg + + def handle_datagram(self, dg): + dgi = DatagramIterator(dg) + msgtype = dgi.read_uint16() + if msgtype in self.handlers.keys(): + self.handlers[msgtype](dgi) + else: + print("Received unhandled message type " + str(msgtype)) # Sending messages @@ -175,7 +534,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? @@ -183,8 +542,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 @@ -198,7 +555,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 @@ -225,7 +582,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 @@ -236,7 +593,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 @@ -308,3 +665,10 @@ 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)) 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. diff --git a/example/astrond.yml b/example/astrond.yml new file mode 100644 index 0000000..aab7265 --- /dev/null +++ b/example/astrond.yml @@ -0,0 +1,58 @@ +# The Daemon section describes identification information which can be queried from the MD. +daemon: + name: Core Message Director # To be used in page titles and intra-MD links. + +general: + eventlogger: 127.0.0.1:9090 + dc_files: + - example.dc + +# Actually just DOGs, not *the* UberDOG. +uberdogs: + - id: 20000 + class: PointOfContact + anonymous: true # May be contacted by status New clients to be Established + +messagedirector: + bind: 127.0.0.1:7199 + +roles: + - type: clientagent + bind: 0.0.0.0:6667 + version: "SimpleExample v0.2" + client: + type: libastron + # Relocate allows a client to send a ClientObjectLocation message to the server to + # indicate it would like to change the location of an object owned by that client. + # This is a feature specific to the Astron client, a custom client class + # could define its own set of configuration values. + relocate: true # Default: false + add_interest: disabled + # Channels defines the range of channels this clientagent can assign to Clients + channels: + min: 100000 + max: 999999 + + - type: stateserver + control: 1000 + + - type: database + control: 1001 + generate: + min: 1000000 # Required (no default) + max: 4294967295 + backend: + type: sqlite3 + database: ./example.db + + - type: dbss + database: 1001 # The channel of the associated database + ranges: + - min: 1000000 + max: 4294967295 + + - type: eventlogger + bind: 127.0.0.1:9090 # REMEMBER: UDP + output: ./events-%Y-%m-%d.log + rotate_interval: 1d + diff --git a/example/example.db b/example/example.db new file mode 100644 index 0000000..e69de29 diff --git a/example/example.dc b/example/example.dc new file mode 100644 index 0000000..0993e75 --- /dev/null +++ b/example/example.dc @@ -0,0 +1,45 @@ +// Some abstractions for readability. +typedef uint32 doId; +typedef uint32 zoneId; +typedef uint64 channel; + +// The Python Views for these distributed classes. +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 PointOfContact { + login(string username, string password) clsend airecv; +}; + +// 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 Avatar { + setXYZH(int16 / 1000, int16 / 1000, int16 / 1000, int16 / 50) broadcast required; + indicateIntent(int16 / 10, int16 / 10) ownsend airecv; +}; diff --git a/example.py b/example/example_client.py similarity index 56% rename from example.py rename to example/example_client.py index 2af2f43..8176198 100755 --- a/example.py +++ b/example/example_client.py @@ -3,12 +3,15 @@ from time import sleep from astron.object_repository import ClientRepository +from shared_constants import POINT_OF_CONTACT_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.') + 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)) @@ -16,14 +19,9 @@ 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() #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' + sleep(0.1) diff --git a/example/example_services.py b/example/example_services.py new file mode 100755 index 0000000..da7c716 --- /dev/null +++ b/example/example_services.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python + +# TODO +# * Catch SIGSTOP +# * Turn --login and --ai into something more generic +# * Proper logging +# * Monitoring output +# * Framerate loop + +import argparse +from time import sleep +import datetime + +from astron.object_repository import InterestInternalRepository as InternalRepository +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 + +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.): + self.host = host + self.port = port + self.frame_time = frame_time + self.repo = InternalRepository(dc_file, + stateserver = stateserver, + dbss = dbss, + ai_channel = ai_channel) + + 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, 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.') + # 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_distobj_db('LoginService', GAME_ROOT_DO_ID, LOGIN_SERVICE_ZONE, set_ai = True) + if self.ai: + print("Starting AI service") + 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 + 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('-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 = 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 new file mode 100644 index 0000000..cffabfb --- /dev/null +++ b/example/example_views.py @@ -0,0 +1,205 @@ +from datetime import datetime + +from astron.object_repository import DistributedObject +from shared_constants import LOGIN_SERVICE_ZONE, WORLD_ZONE, GAME_ROOT_DO_ID, AI_SERVICES_ZONE +import random + +from pprint import pprint + +# Game settings +avatar_speed = 3.0 +avatar_rotation_speed = 90.0 + + +# ------------------------------------------------------------------- +# 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 PointOfContact(DistributedObject): + def init(self): + 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 PointOfContactUD(DistributedObject): + def init(self): + 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.login_services.keys()) > 0: + view = random.choice(self.login_services.values()) + view.login(sender, username, password) + else: + # 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 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.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.login_services.remove(do_id) + print(" PointOfContactUD removed %d from maproot services." % (do_id, )) + +# ------------------------------------------------------------------- +# 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 AIServer(DistributedObject): + pass + +class AIServerAI(DistributedObject): + def init(self): + 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 AIServerAE(DistributedObject): + def init(self): + print("AIServerAE view created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + + def create_avatar(self, sender, client_id): + print(" AIServerAE.create_avatar(sender %d, client_id %d)" % (sender, client_id)) + self.send_update('create_avatar', client_id) + +# ------------------------------------------------------------------- +# Avatar +# * represents players in the scene graph +# * routes indications of movement intents to AI +# * updates the actual position and orientation +# ------------------------------------------------------------------- + +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("AvatarAI created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + +class AvatarAE(DistributedObject): + def init(self): + print("AvatarAE created for %d in (%d, %d)" % (self.do_id, self.parent, self.zone)) + +class AvatarOV(DistributedObject): + def init(self): + 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 new file mode 100644 index 0000000..5856c11 --- /dev/null +++ b/example/shared_constants.py @@ -0,0 +1,27 @@ +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 +STATESERVER = 1000 +DBSS = 1001 + +# 10,000 - 19,999: Internal Repositories +SERVICES_CHANNEL = 10000 + +# 20,000 - 99,999: Fixed-ID Distributed Objects in StateServer +POINT_OF_CONTACT_DO_ID = 20000 + +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 diff --git a/simple_example.dc b/simple_example.dc deleted file mode 100644 index 56662ca..0000000 --- a/simple_example.dc +++ /dev/null @@ -1,30 +0,0 @@ -// Some abstractions for readability. -typedef uint32 doId; -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 -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; -}; - -// 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 { - setXYZH(int16 / 1000, int16 / 1000, int16 / 1000, int16 / 50) broadcast required; - indicateIntent(int16 / 10, int16 / 10) ownsend airecv; -};