Adding an Image File to a HUD Display

Hello everyone, hope this is the right place to get some help but i am in a bit of a jam…

Lately, after playing around with blender, I’ve been getting into the knack of messing around with the Blender Game Engine and after spending time experimenting on the BGE I wanted to spend some of my free time trying to develop an actual video game.

In one of my experimental files, i am trying to recreate a heads up display inspired and based on the HUD from my favorite side scrolling shoot-em-up: GRADIUS. (note: GRADIUS III is my childhood favorite!)

This is what I am aiming for:


This image was made in an image/photo editor as a demonstration but the sprites in the image are real. I am attempting to load the sprites from ‘Speed’ to ‘?/Special’ icons.

This is the code below, using python to attempt to load the sprites saved as PNG:

import bge# import game engine modules
from bge import render
from bge import logic
# import stand alone modules
import bgl


def init():
    """init function - runs once"""
    # create a HUD, use external png file
    avatar_path = logic.expandPath('//materials/heads_up_display/avatar.png')
    speed_path = logic.expandPath('//materials/heads_up_display/speed.png')
    missle_path = logic.expandPath('//materials/heads_up_display/missle.png')
    laser_path = logic.expandPath('//materials/heads_up_display/laser.png')
    option_path = logic.expandPath('//materials/heads_up_display/option.png')
    shield_path = logic.expandPath('//materials/heads_up_display/shield.png')
    special_path = logic.expandPath('//materials/heads_up_display/special.png')
    # store the png indice - to use later
    avatar_source = texture.ImageFFmpeg(avatar_path)
    speed_source = texture.ImageFFmpeg(speed_path)
    missle_source = texture.ImageFFmpeg(missle_path)
    laser_source = texture.ImageFFmpeg(laser_path)
    option_source = texture.ImageFFmpeg(option_path)
    shield_source = texture.ImageFFmpeg(shield_path)
    special_source = texture.ImageFFmpeg(special_path)


    # set the image rendering routine to run every frame
    scene = logic.getCurrentScene()
    scene.post_draw = [render]




def hud():
    """render on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()


    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()


    # rendering routine
    special_source.position((width * 0.2), (height * 0.3))
    special_source.draw


#the command at the end to test the rendering (But nothing comes up)
hud()

This code was from one of the examples of the Blender Python API used to load fonts but remodified to load images instead. I do have some knowledge of python (While I am still learning some more) but so far the code does not work and the only error i got is this:

“global name “special_source” is not defined.”

I was attempting to render out the ‘?/Special’ PNG but it didn’t work and I can already tell that there are more things within this code that is so wrong but I did gave it my best to try at least.

If anybody has a good knowledge of Python scripting in Blender please, let me know. Hopefully we can learn a little something within the python coding that will continue to improve the Blender Gaming Engine beyond its own limits. :slight_smile:

(P.S. Hopefully this is the right place to post this and that this information was not too much… if not, then… WHOOPS.)

There is no need to do it in this way.

  • Create a plane
  • Set up UV coordinates on the mesh in UV Editor
  • assign a material
  • assign a texture
  • assign an image to the texture
  • ensure Mapping Coordinates are set to UV (default is Generated)

No magic, nothing complex, no Python.

Beside of that, Python already tells you what is wrong. Just read it again:

global name “special_source” is not defined.

So you are missing something.

Since you’re already using Python, look into Bgui. I’d recommend grabbing the latest dev version (click the download zip on the right-hand side of the page).

Thanks for the info! I’m sure any of these suggestions that you recommend will be of good use! I’ll be sure to give them a try to see if they work and that it does help bring the graphics to the HUD. :slight_smile:

I appreciate all the help so far!

(EDITED: )

Alright, so using the BGUI that was suggested by Moguri I am actually close to rendering out a graphical image on the HUD.

Here is what I modified so far: (This was used from one of the example codes of the BGUI but modified to only render out a single image)

import sys

# So we can find the bgui module
sys.path.append('..')


import bgui
import bgui.bge_utils
import bge




class SimpleLayout(bgui.bge_utils.Layout):
    """A layout showcasing various Bgui features"""


    def __init__(self, sys, data):
        super().__init__(sys, data)


        # Add widgets here
        
        # Use an avatar image
        self.avatar = bgui.Image(self, '../materials/heads_up_display/avatar.png', name = 'avatar', aspect = None,
            size = [1, 1], pos=[0, 0], texco=[(0, 0), (1, 0), (1, 1), (0, 1)], interp_mode=[BGUI_LINEAR], sub_theme='', options=0)
        
def main(cont):
    own = cont.owner
    mouse = bge.logic.mouse


    if 'sys' not in own:
        # Create our system and show the mouse
        own['sys'] = bgui.bge_utils.System('../../themes/default')
        own['sys'].load_layout(SimpleLayout, None)
        mouse.visible = True
    else:
        own['sys'].run()

The code works, but the image isn’t showing up somehow… Maybe i’m missing something that isn’t rendering in the game engine?

Any ideas or suggestions would be appreciated or otherwise I’ll still investigate how to render out this sucker!

(P.S. If anybody would like to request the blend file along with the code to see how this works or if you can find out what is wrong with this, let me know! I’d like to share along what progress I’ve made. Sharing is caring after all!)

GOOD NEWS: IT FINALLY WORKS! I went through a few knicks and problems but now I have an actual image file on the HUD! I’m still in the work of implementing the graphics and in the end, i’ll let you know how it works!

So the code actually works and I’ve managed to get the images on the screen, but now the problem is that when if I want to clear out the GUI to allow different GUI’s to appear it won’t work. I tried to modify the current code I’m working on to detect if an object (An ‘Empty’) does or does not exist. If it does exist, it should still render it out, while it does not exist anymore the GUI is still there, but not doing anything, updating, or being removed.

I’ve tried to use the bgui.remove_layout(<insert>) to remove the GUI on the detecting the object but once again it does not work:

import sys

# So we can find the bgui module
sys.path.append('..')


import bgui
import bgui.bge_utils
import bge


cont = bge.logic.getCurrentController()
obj = cont.owner
GameObject = obj


class SimpleLayout(bgui.bge_utils.Layout):
    """A layout showcasing various Bgui features"""


    def __init__(self, sys, data):
        super().__init__(sys, data)
        
        player = 'Corruptinator'


        speedup = (GameObject["speed_input"])
        missleup = (GameObject["missle_input"])
        laserup = (GameObject["laser_input"])
        optionup = (GameObject["option_input"])
        shieldup = (GameObject["shield_input"])
        specialup = (GameObject["special_input"])
        
        # Add widgets here


        # Use an avatar image
        #self.avatar = bgui.Image(self, '../materials/heads_up_display/HUD example.jpg', size = [1, 1], pos=[0, 0], options=0)


        # Use an avatar image


        self.avatar = bgui.Image(self, '../materials/heads_up_display/avatar.png', size = [0.165, 0.165], pos=[0.115, 0.016], options=0)
        self.player_name = bgui.TextBlock(self, text = 'Pilot '+player, font = '../misc/Other-F.ttf', pt_size = 40,size = [1,1], pos = [0.24,-0.838])
        
        # Using the Normal Sprites
        if speedup == False:
            self.speed = bgui.Image(self, '../materials/heads_up_display/speed.png', size = [0.165, 0.165], pos=[0.191, 0.016], options=0)
        if missleup == False:
            self.missle = bgui.Image(self, '../materials/heads_up_display/missle.png', size = [0.165, 0.165], pos=[0.297, 0.016], options=0)
        if laserup == False:
            self.laser= bgui.Image(self, '../materials/heads_up_display/laser.png', size = [0.165, 0.165], pos=[0.403, 0.016], options=0)
        if optionup == False:
            self.option = bgui.Image(self, '../materials/heads_up_display/option.png', size = [0.165, 0.165], pos=[0.509, 0.016], options=0)
        if shieldup == False:
            self.shield = bgui.Image(self, '../materials/heads_up_display/shield.png', size = [0.165, 0.165], pos=[0.615, 0.016], options=0)
        if specialup == False:
            self.special = bgui.Image(self, '../materials/heads_up_display/special.png', size = [0.165, 0.165], pos=[0.721, 0.016], options=0)
    
        # Using the Highlighted Sprites
        if speedup == True:
            self.speed_highlighted = bgui.Image(self, '../materials/heads_up_display/speed_highlighted.png', size = [0.165, 0.165], pos=[0.191, 0.016], options=0)
        if missleup == True:
            self.missle_highlighted = bgui.Image(self, '../materials/heads_up_display/missle_highlighted.png', size = [0.165, 0.165], pos=[0.297, 0.016], options=0)
        if laserup == True:
            self.laser_highlighted = bgui.Image(self, '../materials/heads_up_display/laser_highlighted.png', size = [0.165, 0.165], pos=[0.403, 0.016], options=0)
        if optionup == True:
            self.option_highlighted = bgui.Image(self, '../materials/heads_up_display/option_highlighted.png', size = [0.165, 0.165], pos=[0.509, 0.016], options=0)
        if shieldup == True:
            self.shield_highlighted = bgui.Image(self, '../materials/heads_up_display/shield_highlighted.png', size = [0.165, 0.165], pos=[0.615, 0.016], options=0)
        if specialup == True:
            self.special_highlighted = bgui.Image(self, '../materials/heads_up_display/special_highlighted.png', size = [0.165, 0.165], pos=[0.721, 0.016], options=0)
        
def main(cont):
    own = cont.owner
    mouse = bge.logic.mouse


    if 'sys' not in own:
        # Create our system and show the mouse
        
        if GameObject.invalid: # Was supposed to detect of the object does not exist to remove the GUI
            own['sys'].remove_layout(SimpleLayout)
        else:
            own['sys'] = bgui.bge_utils.System('../../themes/default')
            own['sys'].load_layout(SimpleLayout, None)
            mouse.visible = True
            
    else:
        
        if GameObject.invalid: # Was supposed to detect of the object does not exist to remove the GUI
            own['sys'].remove_layout(SimpleLayout)
        else:
            own['sys'].load_layout(SimpleLayout, None)

Right where it says “# Was supposed to detect of the object does not exist to remove the GUI” is where the detection part is, where still it is not functional. There are no errors but you know what I am talking about.

Any ideas? Suggestions? I’m so close to ending this code right now. It’s just this one tiny problem!


import sys

# So we can find the bgui module
sys.path.append('..')


import bgui
import bgui.bge_utils
import bge


cont = bge.logic.getCurrentController()
obj = cont.owner
GameObject = obj


class SimpleLayout(bgui.bge_utils.Layout):
    """A layout showcasing various Bgui features"""


    def __init__(self, sys, data):
        super().__init__(sys, data)
        
        player = 'Corruptinator'


        speedup = (GameObject["speed_input"])
        missleup = (GameObject["missle_input"])
        laserup = (GameObject["laser_input"])
        optionup = (GameObject["option_input"])
        shieldup = (GameObject["shield_input"])
        specialup = (GameObject["special_input"])
        
        # Add widgets here


        # Use an avatar image
        #self.avatar = bgui.Image(self, '../materials/heads_up_display/HUD example.jpg', size = [1, 1], pos=[0, 0], options=0)


        # Use an avatar image


        self.avatar = bgui.Image(self, '../materials/heads_up_display/avatar.png', size = [0.165, 0.165], pos=[0.115, 0.016], options=0)
        self.player_name = bgui.TextBlock(self, text = 'Pilot '+player, font = '../misc/Other-F.ttf', pt_size = 40,size = [1,1], pos = [0.24,-0.838])
        
        # Using the Normal Sprites
        if (speedup == False) == True:
            self.speed = bgui.Image(self, '../materials/heads_up_display/speed.png', size = [0.165, 0.165], pos=[0.191, 0.016], options=0)
        if (missleup == False) == True:
            self.missle = bgui.Image(self, '../materials/heads_up_display/missle.png', size = [0.165, 0.165], pos=[0.297, 0.016], options=0)
        if (laserup == False) == True:
            self.laser= bgui.Image(self, '../materials/heads_up_display/laser.png', size = [0.165, 0.165], pos=[0.403, 0.016], options=0)
        if (optionup == False) == True:
            self.option = bgui.Image(self, '../materials/heads_up_display/option.png', size = [0.165, 0.165], pos=[0.509, 0.016], options=0)
        if (shieldup == False) == True:
            self.shield = bgui.Image(self, '../materials/heads_up_display/shield.png', size = [0.165, 0.165], pos=[0.615, 0.016], options=0)
        if (specialup == False) == True:
            self.special = bgui.Image(self, '../materials/heads_up_display/special.png', size = [0.165, 0.165], pos=[0.721, 0.016], options=0)
    
        # Using the Highlighted Sprites
        if speedup == True:
            self.speed_highlighted = bgui.Image(self, '../materials/heads_up_display/speed_highlighted.png', size = [0.165, 0.165], pos=[0.191, 0.016], options=0)
        if missleup == True:
            self.missle_highlighted = bgui.Image(self, '../materials/heads_up_display/missle_highlighted.png', size = [0.165, 0.165], pos=[0.297, 0.016], options=0)
        if laserup == True:
            self.laser_highlighted = bgui.Image(self, '../materials/heads_up_display/laser_highlighted.png', size = [0.165, 0.165], pos=[0.403, 0.016], options=0)
        if optionup == True:
            self.option_highlighted = bgui.Image(self, '../materials/heads_up_display/option_highlighted.png', size = [0.165, 0.165], pos=[0.509, 0.016], options=0)
        if shieldup == True:
            self.shield_highlighted = bgui.Image(self, '../materials/heads_up_display/shield_highlighted.png', size = [0.165, 0.165], pos=[0.615, 0.016], options=0)
        if specialup == True:
            self.special_highlighted = bgui.Image(self, '../materials/heads_up_display/special_highlighted.png', size = [0.165, 0.165], pos=[0.721, 0.016], options=0)

def main(cont):
    own = cont.owner
    mouse = bge.logic.mouse

    if 'sys' not in own:
        # Create our system and show the mouse
        
        if Was_supposed_to_detect_of_the_object_does_not_exist_to_remove_the_GUI():
            own['sys'].remove_layout(SimpleLayout)
        else:
            own['sys'] = bgui.bge_utils.System('../../themes/default')
            own['sys'].load_layout(SimpleLayout, None)
            mouse.visible = True
            
    else:
        
        if Was_supposed_to_detect_of_the_object_does_not_exist_to_remove_the_GUI(): 
            own['sys'].remove_layout(SimpleLayout)
        else:
            own['sys'].load_layout(SimpleLayout, None)
            
def Was_supposed_to_detect_of_the_object_does_not_exist_to_remove_the_GUI():
    return Main()

def Main():
    object = "object"
    operate = "you"
    do = "want" 
    main = "I"
    primary = "know"
    word = "with"
    execute = "execute"
    basic = "do"
    final = "how" 
    major = "not"
    run = "code"
    other = "imaginary"
    statement = "an"
    process = "to"
    print(main, basic, major, primary, final, operate, do, process,
            execute, run, word, statement, other, object)
    
    return should_the_gui_be_removed()

def should_the_gui_be_removed():
    image_names = [ "May", "bee"[:2], "youth"[:3], "bet", "terminate"[:-6],
                    "return"[:2], "move", "the","go".capitalize()[-2], 
                    "ruin".upper()[-3:-1], "morf"[::-1], 
                    "main"[-3], "difluoromethylornithine"[:-20],
                    "referent"[2:], "abolition"[-2:0:-6], "reject"[2:]]
    print( "{0}{1} {2} {3}{4} {5}{6} {7} {8}{9} {10} {11} {12}{13} {14}{15}.


".format(*image_names) )

o_O" “Ummm…” *ERROR, CORRUPTINATOR.EXE HAS STOPPED WORKING DUE TO RANDOM CODE POSTED ON LATEST POST…

‘Ok then, I’ll figure out by myself then, I’m almost done with this code anyway.’

I hope you saw the message in the console :wink: