Gracias Gracias:  0
Resultados 1 al 1 de 1

Tema: Blender Game Networking

  1. #1
    Administrador y fundador. Avatar de 3dpoder
    Fecha de ingreso
    Apr 2002

    Blender Game Networking

    Blender Game Networking
    by Brian Cordell Hynds

    Through this tutorial, we will create a working server/client for use in the Blender Game Engine. You will be introduced to low level Python networking through the use of sockets. Everything will be covered step-by-step and illustrated, and the completed tutorial files are available for download.

    PART ! Networking And Scripting
    Let's take a minute to explain a few things about networking. I could write an entire encyclopedía on computer networking, but I don't feel you need to know much more than the very basics of what a packet is. You don't need to fully understand this next part, but it's included for the sake of those who may. When a computer needs to send data to another computer, it sends a packet of information across a physical medium to the receiving end. This packet is encapsulated with header information that tells where the packet needs to go. When the packet is sent and received, it flows through a standard known as the OSI model. The only thing you need to know about the OSI model (and the TCP/IP model) is that it works. Packets are sent through a service that is associated to a port. A port is simply a number that TCP uses to send and receive information.

    Now that I've summarized about six months of networking school into one paragraph, take a look at this next diagram: This is a simple chart demonstrating how we will be setting up our server and client. The client will connect to the server and a socket connection will be established. The client will send a string of data to the server. The server will then read the data and send it right bak to the client and close the connection. That's it. This model is known as an Echo server, since it's sole function is to repeat the data bak to the client.

    First, fire up Blender. To avoid the hassle of going step-bystep through creating a game menú, I've taken the liberty of creating one for demonstration purposes. You can download the file from the link at end of the article.

    Lets take a look at what we have here. In a nutshell, there's a camera, 3 inputs (server IP, port, and message), along with a connection button. There's alos a field for the server's response and an empty that we'll use for the user interface controller. Lets start hooking everything together.

    To get some interaction with the game, we're going to need our cursor visible. We'll make a Python script that will do this. Open up the Text Editor window and make a new file called "". This will give me a good opportunity to introduce you to Python scripting, so the rest of the tutorial won't seem as intimidating.

    With Python, we can add almost limitless functionality to our games. Logic bricks are a nice way to add simple functionality without knowing any code, but can become very complex when trying to add functionality that requires more then 20 brik connections. By using Python, we can avoid sorting through a web of brik connections, and extend beyond the limitations that logic bricks hold us to. However, without logic bricks, we would have no way to call our Python scripts.

    Let's get bak to the "" script. We want to make a script that will enable the cursor to be viewed in the game. The Python module that handles this is Rasterzer. To access the Rasterizer functions, we will first need to import the module into our script. After a module is imported, you will have access to all of it's functions. You can import the script using "import [module]". To save typing, we'll use the "as [name]" option. This helps tremendously when creating very long scripts that require you to type the module name a lot.

    import Rasterizer as r
    To show the mouse on screen, we'll use the showMouse() function like this:

    Notice, to call the showMouse() function, we needed to reference the module first. To call any functions contained within a module, you reference them in "module.function().subfunction()" order.

    Another thing to take note of is the function's attribute. In this case, I am using "1" to reference a 'True' value. 'False' is represented as "0". In fact, any non-zero value is a 'True' value. We could have alos used "r.showMouse(True)" and it will work just the same. This is a matter of personal preference, but I think typing "1" and "0" is much faster and easier than 'True' and 'False'.

    Now that our script is made, we need to create some logic bricks that will call them. We'll assign them to our empty, called "GameController". Select the empty and pull up the Logic Bricks window [F4]. Add an Always Sensor and disable True level pulsing. Then add a Python controller. This is where we enter the name of the script to be loaded. Connect the dots, and test out the game. You should now be able to see your cursor in the game view.

    That should give you a good understanding of how Python scripts are handled in the game engine. Now let's get out of beginner mode and have a look at some real coding. From here on out, I'm not going to explain everything as "clik this", "point here", etc. If you're seriously looking to add networking into your games, you should have a good understanding of the basics by now.

    Part 2 : Setting Up the Python Server
    Since we got our beginner course out of the way (quite possibly a primer for some), let's get our basic TCP Python server running. I like to use the Blender Text Editor to edit my scripts, mostly because I hate switching bak and forth between applications. [CTRL+W] will save the .blend file, and [ALT+S] will save the text file outside of the .blend.

    This next script will need to be saved outside of the .blend file, because it will be our server application. I have tried to find ways to run the server easily within the game itself, but I cannot find any easy way to do this. Running it outside of Blender will alos make it much faster in responding and handling client connections.

    So lets have a look at the heart of the networking relationship, the server. As I mentioned before, we're going to use Python sockets to make the connection between the client and the server. I'm going to show you the TCP Python server we'll be using, and within the code I'll breaque it down into understandable pieces using comments.

    # Let's import the socket module import socket
    # Assign a port number to a variable. Assigning values such as this makes
    # it much easier to change, instead of having to edit every reference of the
    # port in the script. Note, use a port value above 1024. Popular services, such
    # as ftp, http, etc. use the lower port numbers and this will help to avoid conflict. port = 2020
    # Here is where we will create our socket. We assign the socket to 's' by calling
    # the socket module and socket() function. The socket() attributes tell the socket
    # to create a STREAM socket type from the INET socket family.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Next, we bind the port to the hostname. This will tell the server that we want
    # to use the specified port to listen on.
    s.bind((socket.gethostname(), port))
    # Now lets tell the server to start listening for client connections.
    # For testing purposes, we'll setup the server to handle 1 simultaneous
    # connection. You can change this later if you need. s.listen(1)
    # Since this script will be run outside of the game, most likely in a terminal
    # window, we can use print() to show that the server is running. I've included
    # the port value in the command to display the port number.
    print "Game server is running on port", port
    # This is our main loop to handle incoming client connections.
    # Connections are accepted and the message is stored into a variable.
    # The connection information is print() 'ed to the terminal window and the message
    # is then sent bak to the client. Then the connection is closed.
    while 1: conn,
    addr = s.accept()
    data = conn.recv(1024)
    # display client connection información
    print "connected...", addr, data
    Save this file as "". If you created the file inside of blender, use ALT+S to save it outside of the .blend. Then open up a terminal window, navigate to the directory where you saved the server script, and type "python" to run the server. You should see something like this:

    $ python

    Game server is running on port 2020
    To properly kill the process, use the "top" command and search for the "Python" listing under Command. Remember the PID next to it and press the que key to exit top. Then use the command "kill [pid]" replacing [pid] with the PID of the Python command from top. After it's executed, you should notice a "Terminated" command at the end of your server.

    Part 3 : Creating the Client
    Now that we have a running server, it's not going to do much if we don't create our clients. Using the .blend file from the previous articles (here), let's set a few things up before creating the client code.

    First off, if you look at the menú, you'll notice there are 3 inputs: Server IP (input1), Port (input2) and Message (input3) are used to create the connection with the server. Currently, there's no easy way to enter the data for múltiple text objects, so we'll have to script it.

    Before we do, select each input object and create two properties. The first one being a string named "Text" and the second one as a bool named "edit". Set input1's edit property to True, and the others to false. This will give us somewhere to start.

    I'm just going to summarize the script, instead of walking you through it step-by-step. We create a trigger that checks to see if a Sensor (a Keyboard Sensor) is positive. If it is, then we create a Python list of the 3 input objects. Then, we run an if/elif loop to set the "edit" properties of the appropriate inputs according to which conditional statement is true. Simple enough.

    Here's the script. Save this as "" in the Blender Text Editor.

    import GameLogic as gl
    cont = gl.getCurrentController()
    trigger = cont.getSensor("tabcheck")
    if trigger.isPositive():
    # get objects
    input1 = gl.getCurrentScene().getObjectList()["OBinput1"] # server ip
    input2 = gl.getCurrentScene().getObjectList()["OBinput2"] # port
    input3 = gl.getCurrentScene().getObjectList()["OBinput3"] # message
    proplist = [input1, input2, input3]
    # server => port
    if (proplist[0].edit == 1):
    proplist[0].edit = 0
    proplist[1].edit = 1
    proplist[2].edit = 0
    # port => message
    elif (proplist[1].edit == 1):
    proplist[0].edit = 0
    proplist[1].edit = 0
    proplist[2].edit = 1
    # message => server
    elif (proplist[2].edit == 1):
    proplist[0].edit = 1
    proplist[1].edit = 0
    proplist[2].edit = 0
    Select the "GameController" empty and setup a Keyboard Sensor. For this exercise, I am going to be using the Return key, simply because using the Tab key actually produces "@" key returns which mess up the text input. You could use the Tab key if you want, but you'll have to edit the script to remove the "@" in the text object. Connect this Keyboard Sensor to a Python Controller, and use the "" file.

    Here's where a few problems lie within the logic brik design. What we need to do is create two Mouse Sensors ("Mouse over" and "Left button"), and when they are both positive a Python script is started. At first glance you might think, "Well, hooque them both up to a Python script controller". This isn't going to work because each Mouse Sensor will act independently as if it were an OR condition, and the script will run every time a left mouse button is pressed and every time you mouse over the button. We need to connect them to an AND controller, but now we're presented with the problem of not being able to run the script directly. Since there is no Python Actuator, we're going to use the Property Actuator to set a bool property, which will trigger a Property Sensor that will initialize the script. Take a look at the image below to see how this works: Onto the script. Much like the server script, I'm going to show you the script we'll be using, and then use comments within the script to explain what's going on.

    # Since we'll be using Blender Game Engine functions,
    # we need to import the GameLogic module.
    import socket
    import GameLogic as gl
    # This is another problem with the logic bricks. We can initialize scripts using the
    # Python controller, but we can't stop them when their sensor is not true. If we don't
    # chek the property, the script will actually run twice (on clik and on release).
    # We'll create a loop to test if the property is true, this way we only run it once.
    conprop = gl.getCurrentController().getOwner()
    if (conprop.connect == True):
    # Now let's get the "Text" property values from the input objects, and assign
    # them to respective variables. Notice that we need to use the int() function
    # for the port settings. If we don't, the variable is assigned as a string, and
    # you will get an error when binding the port because it's not an integer value.
    hostinput = gl.getCurrentScene().getObjectList()["OBinput1"]
    host = hostinput.Text
    portinput = gl.getCurrentScene().getObjectList()["OBinput2"]
    portstring = portinput.Text
    port = int(portstring)
    # As with the server, we create the socket.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Instead of listening for connections, we'll connect to the server.
    s.connect((host, port))
    # We'll grab the message from input3 and use the the send() function
    # to send it to the server.
    message = gl.getCurrentScene().getObjectList()["OBinput3"]
    sendme = message.Text
    # Assign the server response to a variable,
    # so we can use it later, and close the connection.
    data = s.recv(1024)
    # Now we can display the echoed message in the server response
    # text object by assigning it to it's Text property.
    resp = gl.getCurrentScene().getObjectList()["OBresponseValue"]
    resp.Text = data
    # And finally, we reset the connect property bak to false.
    conprop.connect = 0 Summary
    Let's test it all out. Fire up the server, then play the game. Type in the IP of the server, the port number the server is running on, and a message you'd like to send. Press connect, and if all went well, the server should respond with your echoed message which is displayed in the response área. You can see the connections printed in the server terminal window. Hopefully, this will have given you a good understanding how simple socket connections are made and how you can get networking within your games.

    You can download the entire .blend file, which includes the server and the game client, here.

    In my next article, we'll cover how to design a simple Python chat server, complete with password authentication, and setting up the Blender UI to create a chat client in the game engine.

    Until then, if you have any questions, comments, or problems, feel free to e-mail me at, or jump into the discussion at BlenderArtists in this forum thread:

    By Brian Cordell Hynds

    Miniaturas adjuntadas Miniaturas adjuntadas Blender Game Networking-1.jpg   Blender Game Networking-2.jpg   Blender Game Networking-3.jpg   Blender Game Networking-4.jpg  

    Blender Game Networking-5.jpg  
    Si vas a subir un trabajo al foro, hazlo adjuntando la imagen, archivo, vídeo o lo que sea, no publicando enlaces de otros sitios.

    |Agradecer cuando alguien te ayuda es de ser agradecido|

Temas similares

  1. Ofertas de Trabajo Opera Game Studio busca URGENTE - Programador C# Networking Unity3D
    Por Stratos en el foro Colaboraciones e Iniciativas
    Respuestas: 0
    Último mensaje: 16-01-2016, 10:37
  2. Ofertas de Trabajo Opera Game Studio busca Programador C# Networking Unity3D
    Por Stratos en el foro Colaboraciones e Iniciativas
    Respuestas: 0
    Último mensaje: 12-01-2016, 10:37
  3. Ofertas de Trabajo Opera Game Studio busca Programador C# Networking Unity3D
    Por Stratos en el foro Colaboraciones e Iniciativas
    Respuestas: 0
    Último mensaje: 17-12-2015, 10:37
  4. Blender game engine
    Por GEKKONIDAE en el foro Blender
    Respuestas: 21
    Último mensaje: 09-10-2008, 14:27
  5. :::Blender 2 31a mas Raytrace mas game engine Blender Power :::
    Por SHAZAM en el foro Infografía General
    Respuestas: 18
    Último mensaje: 14-01-2004, 13:34

Actualmente estos son sus permisos de publicación en el foro.

  • -No puedes crear nuevos temas al no estar registrado o no haber iniciado sesión en el foro.
  • -No puedes responder temas al no estar registrado o no haber iniciado sesión en el foro.
  • -No puedes subir archivos adjuntos al no estar registrado o no haber iniciado sesión en el foro.
  • -No puedes editar tus mensajes al no estar registrado o no haber iniciado sesión en el foro.