BGHelper Refactored

Hey, there. So, I started this module, the BGHelper module, many moons ago to help with making games. The module ended up being heavy and kind of awkward to use. So, I’ve started to refactor the entire thing from scratch, adding new features, fixing broken ones, and keeping track of my organization. All of my modules and resources will be under this umbrella, and will feature a singular example blend file with difference scenes to show the different uses of the module (theoretically).

So far I have an example for some of the different parts of the module, and have otherwise just been working on progressively refactoring the code. The new BGHelper module covers:

  • 2D Sprites, achieved via SpriteMaps (objects that you can add animations to, set callbacks for their operation, and do other nifty things)
  • Viewports, added via a manager object
  • Window resizing
  • Easy audio playback using a base audio directory (i.e. “//assets/sound/”)
  • 2D Filter library containing filters like bloom, scanlines, a Game-boy like filter, and others as well.
  • API-related functions, like the ability to end the game on the first error.
  • A built-in mouse-look function with customizable arguments.
  • Useful math functions, like Lerping, Clamping, and returning the Sign of a number. Also, the ability to cast multiple rays on a single line.
  • A mesh “wrapper” that allows for determined polygon indexing (i.e. so that you will always be able to access a specific polygon).
  • Random level generation (my old RLG module).
  • Lots of other cool stuff.

Anyway, you can grab the entire thing via SVN from my Google Code page here.

This is pretty kewl SolarLune you have been doing allot of work for the benefit of the community, so from me at least, thank you!!! I was going to do the same thing then I found this, maybe this should be the sole library for already made functions should really be in a sticky… MODS :wink: . I would like to add some functions if that is ok?

Thanks, I appreciate it. Yeah, sure, adding things should be fine - what functions are you thinking of adding? P.S. I’ve added a MouseOrbit function that I made for someone on the forums here - I’m waiting for a little more before I release this, though.

I wanted to add a trackTo function as an alternative to using the brick, this is what ive done so far but its not quite working correctly yet.

########################################
#   Useful Object Modifier Functions
#    by Siegel
#     Blender 2.5x
########################################

import time
import bge

def trackTo(fromOb, toOb, delay, axis):
    if delay <= 0:
        vect = fromOb.getVectTo(toOb)
        fromOb.alignAxisToVect(vect[1], axis)
    else:
        if fromOb.__contains__("trackTo"):
            fromOb["trackTo"][1] = time.clock()
            diff = fromOb["trackTo"][1]-fromOb["trackTo"][0]
            if diff >= delay:
                print(diff)
                fromOb["trackTo"][0] = time.clock()
                fromOb["trackTo"][2] = toOb.worldPosition.copy()
            print(fromOb["trackTo"][2])
            vect = fromOb.getVectTo(fromOb["trackTo"][2])
            fromOb.alignAxisToVect(vect[1], axis)
        else:
            print("once")
            fromOb["trackTo"] = [time.clock(),0.0, toOb.worldPosition.copy()]

I’d like to see how this works. It’s an interesting idea, and I like the addition of this function rather than the logic brick.

tried working on it some more, is following rather than track atm and does some wierd stuff sometimes will redo it again later.

########################################
#   Useful Object Modifier Functions
#    by Siegel
#     Blender 2.5x
########################################

import time
import bge

def trackTo(fromOb, toOb, delay, axis, threeD):
    if delay == 0: #if delay is 0 then track everytime script runs
        vect = fromOb.getVectTo(toOb)
        fromOb.alignAxisToVect(vect[1], axis)
    else: #if delay > 0 
        if fromOb.__contains__("trackTo"): #check property if not there first time script is running
            if len(fromOb["trackTo"][2]) < 2: #if tracker list is to small to chech against just add to it
                fromOb["trackTo"][2].append(toOb.worldPosition.copy())
            else:
                if fromOb["trackTo"][2][len(fromOb["trackTo"][2])-1] != toOb.worldPosition.copy(): #basically checks if object being tracked is moving if not dont update tracker list
                    fromOb["trackTo"][2].append(toOb.worldPosition.copy())
            fromOb["trackTo"][1] = time.clock()
            diff = fromOb["trackTo"][1]-fromOb["trackTo"][0]
            if diff >= (delay/(len(fromOb["trackTo"][2])))/10: #if the delay is sufficient track to first position in tracker list
                fromOb["trackTo"][0] = time.clock()
                vect = fromOb.getVectTo(fromOb["trackTo"][2][0])
                if threeD == 0:
                    vect[1].z = 0
                fromOb.alignAxisToVect(vect[1], axis)
                fromOb["trackTo"][2].remove(fromOb["trackTo"][2][0])            
        else: #if property not there first time script is running so create property
            fromOb["trackTo"] = [time.clock(),0.0, [toOb.worldPosition.copy()]]
            
ol = bge.logic.getCurrentScene().objects

trackTo(ol["1"], ol["2"], 50, 1, 0)

Man im such an idiot it was so simple all along, here is the final version of the trackTo function.

########################################
#   Useful Object Modifier Functions
#    by Siegel
#     Blender 2.5x
########################################

import bge

def trackTo(fromOb, toOb, delay, axis, threeD):
    vect = fromOb.getVectTo(toOb)
    if threeD == 0:
        vect[1].z = 0
    fromOb.alignAxisToVect(vect[1], axis, 0.1/delay)

ol = bge.logic.getCurrentScene().objects

trackTo(ol["1"], ol["2"], 5, 1, 0)

Aha - I worked on this too, but I couldn’t make any headway. I was going to convert the object’s orientation into a Euler, then into a Vector point in space so that I could Linear Interpolate between that and the destination point! This is so much simpler! Thanks, I’ll add it into the next release (which probably will be today), and credit you for it. Thanks, a lot!

EDIT: I’m going to change variable names and some other stuff around, though, to keep the code consistent (for example, no style changes between functions). I hope that’s alright.

Updated to V1.1 - Siegel’s TrackTo function added, along with two mouse orbiting functions. Also, a couple of pi and vector-related variables have been added. In addition, an example file with multiple scenes has been packaged that shows some of the features of the BGHelper module in action.

change it as you like just glad for the credit, I added in a bit of code to make it a bit more versatile.

def TrackTo(dest, obj = None, time = 0, axis = 0, dimensions = "xy"):

    """
    Track To function equivalent to the track to actuator.
    Contributed by Siegel.
    
    dest = destination object (or point) to track to
    obj = source object to rotate; if set to None or omitted, it defaults to the object running the script
    time = time value to rotate the source object by (in seconds)
    axis = which axis to align the source object to the destrination point; 0 = X, 1 = Y, 2 = Z
    dimension = specify which axis to track on
    """
    
    if obj == None:
        obj = logic.getCurrentController().owner

    vect = obj.getVectTo(dest)
    if dimensions.count("x") == 0:
        vect[1].x = 0
    if dimensions.count("y") == 0:
        vect[1].y = 0
    if dimensions.count("z") == 0:
        vect[1].z = 0
    if time > 0:
        obj.alignAxisToVect(vect[1], axis, 0.1/time)
    else:
        obj.alignAxisToVect(vect[1], axis)

Thanks, I’ll add it in to the next release. Glad to have people that want to add features and functions to a community helping module / project.

Here is another one I find quite handy.


########################################
#   random number within range
#    by Siegel
#     Blender 2.5x
########################################

def randomRange(min, max, rounded):
    if rounded:
        return(round(min+bge.logic.getRandomFloat()*(max-min)))
    else:
        return(min+bge.logic.getRandomFloat()*(max-min))

i find out, that a self made trackTo function is much slower than the Actuators. If you have hundreds of objects tracking to something, you’ll see it. But sometimes, its eaysier to to use this method. Therfore: nice to have!

for randomRange you could use the random module:


# randomRange

import random
rint = random.randint(-10,10)# returns an integer from -10 to 10
rflt  = random.uniform(-10,10)# returns a float from -10 to 10
r     = random.random()# returns a float between 0 and 1.0

@sevi - It’s actually slower? Too bad - I hoped that the speed would be comparable… I’ll have to do some tests. Thanks for the information - also, yes, the random module is useful for getting random numbers… Though, I think I already made a random number function in the module similar to Siegel’s! LOL

if anybody want to test it, you could download this:
http://www.blendpolis.de/download/file.php?id=62668

this is a swarm simulator i made… (not finished and buggy…and only runs on 2.56a , r 34074)

For this i tried several ways to make the swarmunits track. I ended up with simple trackTo actuators for the fastest, self made TrackTo for second, and OOP for slowest solution.
This is probably because the logic bricks are written in C++(i think) and python interpretes this. I read somewhere, that the speed increase is about 200 to 1000 times.
But, i dont know it exactly, because i dont know C,C++, C whatever, except of “helle World” ok…:wink:

edit:

i just thought, if you not track to every frame, it could even be faster?

Thanks for the test, I’ll check it out.

Sounds about right, anything hard coded in C/C++ is gonna run faster than something done through the python interpreter, main reason behind using a python function over the brick is versatility if you can spare the processing power for it. Should be able to increase performance by limiting pulse frequency and adjusting “0.1/time” to compensate while still getting good results, ill have a looksee at your example and see if i can get it working a bit faster.

couldn’t get your file working so did a little stress test of my own and the function seems to hold up as well as the actuator brick does,
have a look, controls are wasd, spacebar. There are two scenes one using the function the other using the brick. Made using official blender 2.57b. http://www.pasteall.org/blend/6648

well, thats pretty interesting, seems to be equivalent performance.
There is one thing: The function has to be actualised every frame, while the bricks dont need a pulse mode at all.
But still then, there is no effect. Nice !!

I tested my theory, but the speed didn’t increase at all. Oh, well - must have been some sort of overhead associated with the process…