Friday, September 23, 2016

Python3 Asyncio PubSub Plaything


#!/usr/bin/env python
import io
import asyncio
import websockets
import logging
import collections

logger = logging.getLogger('websockets.server')
logger.setLevel(logging.ERROR)
logger.addHandler(logging.StreamHandler())
events = collections.defaultdict(lambda: set())
#-----------------------------------------------------------------------
async def handle_outgoing_queue(websocket):
    while websocket.open:
        msg = await websocket.outbox.get()
        await websocket.send(msg)
#-----------------------------------------------------------------------
async def pubsub(websocket, path):
    websocket.prefix = path.encode()
    websocket.outbox = asyncio.Queue()
    websocket.subscriptions = set()
    sender_task = asyncio.ensure_future(handle_outgoing_queue(websocket))
    while True:
        msg = await websocket.recv()
        if msg is None: break
        if isinstance(msg, str): msg = msg.encode()
        stream = io.BytesIO(msg)
        await handle_message(websocket, stream)
    sender_task.cancel()
    for name in websocket.subscriptions:
        try:
            events[name].remove(websocket)
        except KeyError:
            pass
#-----------------------------------------------------------------------
async def handle_message(websocket, stream):
    cmd = stream.readline().strip()
    name = websocket.prefix + stream.readline().strip()
    print(cmd, name);
    if cmd == b"SUB":
        events[name].add(websocket)
        websocket.subscriptions.add(name)
    elif cmd == b"UNS":
        subscribers = events[name]
        try:
            websocket.subscriptions.remove(name)
        except KeyError:
            pass
        try:
            subscribers.remove(websocket)
        except KeyError:
            pass
    elif cmd == b"PUB":
        stream.seek(0)
        msg = stream.read()
        for subscriber in events[name]:
            await subscriber.outbox.put(msg)
#-----------------------------------------------------------------------
start_server = websockets.serve(pubsub, '0.0.0.0', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Sunday, January 03, 2016

Notes on DragAndDrop in the Unity Editor

The documentation for the Unity DragAndDrop class is a little lacking, so here are the notes from my experiments into how the whole things works and integrates with OnGUI.


* If the current event in your OnGUI function is MouseDrag, first call:

DragAndDrop.PrepareStartDrag ()

then assign a value to DragAndDrop.objectReferences or DragAndDrop.paths and then call:

DragAndDrop.StartDrag(string title)

* If the current event is DragUpdated, you need to check if the drag operation can succeed or fail, then set:

DragAndDrop.visualMode = DragAndDropVisualMode.*

to an appropriate value. Important:If the drag operation could be accepted at this point, call:

DragAndDrop.AcceptDrag()

which will allow the DragPerform event to occur correctly if the mouse button is released.

* If the current event is DragPerform, the drag operation has succeeded and you can perform whatever logic is needed. No further DragAndDrop calls need to be made.

* If the current event is DragExited, you know that the drag operation has ended and you can perform any cleanup needed. Note: This event always occurs, even when DragPerform has completed.




Wednesday, December 09, 2015

Implicit typing in C# using "var"

I use the var keyword everywhere. Someone told me today that this is a bad practice, because "sometimes you can't tell what type it is".

Well, I disagree. I believe we generally don't care what type a variable is, we care about how we use it, the interface it provides to the programmer. For example:
foreach(var i in myListOfThings) {
    Debug.Log(i.name);
}
I don't care what typeof(i) is, I just want to know it has a .name attribute. If I change the type later, I probably still want it to have a .name attribute, and the var keyword lets this code keep working. Also:
var v = new Vector3(0,0,0);
//vs
Vector3 v = new Vector3(0,0,0);
In this case, the Vector3 type declaration is redundant, it is simply repeating information already on the same line. Remember, repeating yourself in code is a Bad Thing. Later on if I realise my Vector3 variables need to be Vector2 variables, I need to change the type information in 2 places for each variable. Yuck.

Finally, var lets me write less characters, which often means less backspacing and retyping!
var now = System.DateTime.Now;
//or
System.DateTime now = System.DateTime.Now;

This well written post describing more advantages of implicit typing. To Summarise:
  • It induces better naming for local variables.
  • It induces better API.
  • It induces variable initialisation.
  • It removes code noise.
  • It doesn't require the using directive.

Monday, November 23, 2015

MOG Server & Client for Unity.

Sometime ago I put my generic multiuser game server (NetWrok) on GitHub. It's written in Python3, uses websockets, postgresql and runs on most platforms.

I have now released the Unity NetWrok Client code.

Wednesday, November 11, 2015

I made a Mosasaur.

Wings3D for modelling. Cheetah3D for UV unwrap and rigging. Substance Painter for Texturing.



Mososaurus
by simonwittber
on Sketchfab

Popular Posts