Tuesday, February 12, 2013

[Tutorial]: database in Blender Game Engine

Hello dear readers, i have been asked by some of my friends in college (computer engineering) how to make blender game engine deal with databases for their graduation project..

after some research, i fonud an easy way that don't need any external dependencies, and should work on any OS with no problems, you don't need MYSQL for that as long as python can deal with SQLite, and blender do support the use of SQLite in it's game engine.

if you are familiar with python you can have a look at this script, otherwise read the explanation of each part of it, it is supposed to be easy to understand once explained.

import os
import GameLogic as G

cont = G.getCurrentController()
own = cont.owner

######## dynamic library import
try:
    import sqlite3
except:
    from pysqlite2 import dbapi2 as sqlite3

######## dynamic path
path = "/Volumes/usbmemory/user_data.db" # this path is for macintosh, change it to windows if you need to.

######## the connection and cursor vars
conn = sqlite3.connect(path)
c = conn.cursor()

######## dynamic table name
user_table = "users"

######## if there is no table at all, create one
if not os.path.exists(path):
    c.execute("create table "+user_table+" (id INTEGER PRIMARY KEY AUTOINCREMENT, name text,gender text,age real,mass real)")
else:
    sqlite3.connect(path)

try:
    c.execute("create table " +user_table+" (id INTEGER PRIMARY KEY AUTOINCREMENT, name text,gender text,age real,mass real)")
except (sqlite3.OperationalError):
    print ("table already exists>>")

######## if there is no row at all, create one

c.execute("SELECT Count(*) FROM "+user_table)
rows_no = c.fetchone()[0]

if rows_no == 0:
    c.execute("insert into "+user_table+" (name, gender, age, mass) VALUES('dave','male',32,96)")

######## to check for the number of rows in a database

c.execute("SELECT Count(*) FROM "+user_table)
print("number of rows :",c.fetchone()[0])

######## fill entries into variables

c.execute("SELECT * FROM "+str(user_table))
gender = (c.fetchall()[-1][2])

c.execute("SELECT * FROM "+str(user_table))
name = (c.fetchall()[-1][1])

c.execute("SELECT * FROM "+str(user_table))
age = (c.fetchall()[-1][3])

c.execute("SELECT * FROM "+str(user_table))
mass = (c.fetchall()[-1][4])

c.execute("SELECT * FROM "+str(user_table))
the_row = (c.fetchall())

# input from user # changed from the entry into text objects
input_name = 'grandma'
input_gender = 'female'
input_age = 88
input_mass = 65

# change stuff
if cont.sensors[1].positive:
    c.execute("UPDATE " +user_table+ " SET   name = "+" ' "+   input_name+" ' "+" WHERE id = 1")
    c.execute("UPDATE " +user_table+ " SET gender = "+" ' "+ input_gender+" ' "+" WHERE id = 1")
    c.execute("UPDATE " +user_table+ " SET    age = "+str(input_age)+" WHERE id = 1")
    c.execute("UPDATE " +user_table+ " SET    mass = "+str(input_mass)+" WHERE id = 1")

# report changes
if cont.sensors[0].positive:
    print("hey "+str(name))
    print(the_row)
    own["name_"] = name
    own["gender_"] = gender
    own["age_"] = age
    own["mass_"] = mass
   
conn.commit()
c.close()
conn.close()

to import Blender's Game Engine and os, use these two commands

import os
import GameLogic as G
the use of os is to use a function where you can check if a file exists or not

we define the owner-object of the script controller and the controller itself in two variables for easier acces in the upcoming lines of the code.
cont = G.getCurrentController()
own = cont.owner


these lines are to make sure that the current version of python you are using has sqlite3 embedded in it, otherwise use sqlite2
######## dynamic library import
try:
    import sqlite3
except:
    from pysqlite2 import dbapi2 as sqlite3

we define the path of the file, the connection and it's cursor, which is used to cross the records from the result set, and the table name could be stored in a string variable.
######## dynamic path
path = "/Volumes/usbmemory/user_data.db" # this path is for macintosh, change it to windows if you need to.

######## the connection and cursor vars
conn = sqlite3.connect(path)
c = conn.cursor()

######## dynamic table name
user_table = "users"

the os.path.exists(path) is used to return true/false for the if check statement, it creates a table with 5 columns, the columns are (id, name, gender, age, mass), the id is important to distingush a row from another, it increments automatically, if the file already exists then the connection will get initiated automatically.
######## if there is no table at all, create one
if not os.path.exists(path):
    c.execute("create table "+user_table+" (id INTEGER PRIMARY KEY AUTOINCREMENT, name text,gender text,age real,mass real)")
else:
    sqlite3.connect(path)

 so you now wonder what do c.execute("") mean? it does execute an SQLite command, that could be data reading/writing/etc.. it takes the string in it and parse it as a command of SQLite, so we can use concatenation to have some of it's content dynamic
c.execute("create table "+user_table+" (id INTEGER PRIMARY KEY AUTOINCREMENT, name text,gender text)")
so we have our string concatenated with a string variable user_table and then again with a given string.

we query the number of rows then we fetch it and have it stored in rows_no variable , if there is now data, insert a new row with the values VALUES('dave','male',32,96)
######## if there is no row at all, create one

c.execute("SELECT Count(*) FROM "+user_table)
rows_no = c.fetchone()[0]

if rows_no == 0:
    c.execute("insert into "+user_table+" (name, gender, age, mass) VALUES('dave','male',32,96)")

we fill the variables gender, name, age, mass with the data of final row [-1]
######## fill entries into variables

c.execute("SELECT * FROM "+str(user_table))
gender = (c.fetchall()[-1][2])

c.execute("SELECT * FROM "+str(user_table))
name = (c.fetchall()[-1][1])

c.execute("SELECT * FROM "+str(user_table))
age = (c.fetchall()[-1][3])

c.execute("SELECT * FROM "+str(user_table))
mass = (c.fetchall()[-1][4])

c.execute("SELECT * FROM "+str(user_table))
the_row = (c.fetchall())


for simplicity we consider these input_name, input_gender, input_age, input_mass to be pre-defined variables while they could be some input from the user

# input from user # changed from the entry into text objects
input_name = 'grandma'
input_gender = 'female'
input_age = 88
input_mass = 65

# change stuff
if cont.sensors[1].positive:
    c.execute("UPDATE " +user_table+ " SET   name = "+" ' "+   input_name+" ' "+" WHERE id = 1")
    c.execute("UPDATE " +user_table+ " SET gender = "+" ' "+ input_gender+" ' "+" WHERE id = 1")
    c.execute("UPDATE " +user_table+ " SET    age = "+str(input_age)+" WHERE id = 1")
    c.execute("UPDATE " +user_table+ " SET    mass = "+str(input_mass)+" WHERE id = 1")

# report changes
if cont.sensors[0].positive:
    print("hey "+str(name))
    print(the_row)
    own["name_"] = name
    own["gender_"] = gender
    own["age_"] = age
    own["mass_"] = mass
 cont.sensors[1].positive returns true if the second sensor in the logic-bricks is triggered, we use UPDATE to change the entries for WHERE  id = 1, if the seccond sensor is triggered, then you can fill your properties and print what you need etc..

we do perform these commands to have the connection commited and the cursor closed
conn.commit()
c.close()
conn.close()


I hope you find my tutorial useful, if you have any suggestions email me, if you face any difficulty refer to SQLite3 documentation, thanks.


 

[Character Rig]: Irvine Rig

Hi
the new fixed version of Irvine rig is here

concept by arild wiro -permitted-
Nathan’s rig is ported and adjusted by lumpycow




an animation by Matthew Dietel “Mokazon”


[Download] the blend

[Model]: Swiss Army Knife

my first model on turbosquid, a swiss army knife 3D model

model name: Swiss Army Knife 3D Model
  • 29,936 Polygons 
  • 29,525 Vertices
  • file format : .blend and .obj
  •  Price 25 Usds

Have a look at the model <Here>

[Tutorial]: Abstract Art

Hi, I just needed some abstractish art for some documents, and told my self: “why not to make my own with Blender?”
I got with the result you see above, they liked the result, and was asked to make tutorial and made it immediately 
the  tutorial covers these items:
  • 3D Modeling
  • Materials
  • Nodes composting
  • And more


an animated example

<Download> the .blend file

[Article]: Electronics & Blender Game Engine


Hello mates, so now it is summer holiday’s first day for me, and I think it’s about time to start working on nice Blender Projects, but before doing so, let me introduce one of my latest humble projects.
Project: Controlling a Stepper motor using an Arduino Interface board
Here goes the Hardware image

  

and the software Image


what do the project do?
it allows you to control the stepper motor with 3D buttons rather than real ones on the breadboard, this illustrates a basic setup, one of the possibilities would be connecting the same hardware to a racing game, the game 3D vehicle would send the velocity signal to the hardware and make the motor velocity controlled according to the 3D Vehicle.
there were some added things like a password for the locker, and other things.
what is arduino?
very basicly, Arduino is an electronic board, where you can tell it to control Electronic elements.
so Arduino can control the video game
example: [tilt sensor moves the vehicle]
or
the video game can control Arduino
example: [when the Vehicle collides with a wall from it's left side, a left L.E.D. [light emitting diode] would be on while the left on is not, or a force feedback of a vibration motor]
are these things complicated?
they can be taught in a book/Manual/Video_tut that covers some stuff
from the electronics field, and other stuff from the BGE field, my knowledge as a Mechatronics Engineering student helped me somehow, but anyone for sure can learn these things.