Render cycle in cocos2d-x - c++

I have a game engine written my my team, it's component based. It has logic components and visual components. In visual components there is a function named updateVisual(delta) and everything is drawn there.
For example, let's take physic ball entity in world:
class LogicBallComponent
{
// ...
};
class VisualBallcomponent
{
sfml::Texture mBallTexture;
void updateVisual(float)
{
mBallTexture.translate(...);
GlobalDisplayManager::instance().draw(mBallTexture);
}
};
GlobalDisplayManager returns some window representation which creates gl-states, etc. (sf::RenderWindow in sfml). This system is easy to integrate.
Now I need to make android-game using my engine. I've chosen cocos2d-x to use for window creation, rendering, fonts, resources etc.
There is another way to do the job:
class Ball : public CLayer
{
bool Ball::init() {
CSprite* sprite = CSprite::create(...);
this->addChild(sprite, 0); // [!]
}
};
And I don't know how to use it in my way. Is there such possibility?

You should check out the function "void CCDisplayLinkDirector::mainLoop(void)", which is the main loop of coco2d-x rendering engine.
coco2d-x provides wrappers for periodic calling loop. In iOS you should check the function startMainLoop of CCDirectorCaller.mm in platform/ios.

Related

QML OpenGL plugin not redrawing at 60Hz

The Situation
My company has a QML-based application which displays some content using a custom OpenGL-based render plugin (MyGame). This plugin has a few critical needs:
To be able to effect changes in the renderer in response to QML-based signals.
(e.g. change the position of an object rendered by the game)
To only process these changes at a specific spot in MyGame's redraw loop.
(This is very important; MyGame is very sensitive about when changes are allowed.)
To have the plugin redraw at 60Hz (at least).
The Problem
The code we have right now honors (1) and (2), but fails (3); the plugin does not get visually updated consistently. (The updates are erratic, at an estimated 5-10Hz.) I believe that the plugin we have created—based on QQuickFramebufferObject—is not taking proper advantage of how Qt/QML intended the scene graph to be updated.
How can I re-structure my plugin so that I get all three of the above?
The Code
Overview:
The plugin creates a QQuickFramebufferObject (MyPlugin) and a QQuickFramebufferObject::Renderer (MyRenderer).
When MyRenderer::render() is called it calls MyGame::Redraw() itself, and then calls update().
MyGame::Redraw() does what it needs to, and at the right spot where changes can be accepted, emits a timeToMakeChanges QML signal on MyPlugin.
QML listens for the onTimeToMakeChanges signal and invokes methods on the plugin that affect MyGame.
To workaround the problem of low-frequency visual updates, I've found that if I overlay a QML Canvas over my plugin and redraw the canvas frequently using a Timer, my plugin starts to get visually updated at what appears to be around 60Hz. Clearly this is a gross hack.
Following is a summary of the code setup. Please forgive missing/incorrect code; I'm trying to distill thousands of lines of glue code down to the essentials for this question.
MyPlugin.h
#include <QOpenGLFramebufferObject>
#include <QQuickFramebufferObject>
class MyPlugin : public QQuickFramebufferObject {
Q_OBJECT
public:
MyPlugin();
virtual ~MyPlugin();
virtual QQuickFramebufferObject::Renderer* createRenderer() const;
signals:
void timeToMakeChanges();
public slots:
void makeChanges(QVariant inValue);
void HandleWindowChanged(QQuickWindow *inWindow);
private:
MyGame* GetGame() { ... }
};
MyPlugin.cpp
#include "MyPlugin.h"
#include <MyGame.h>
// ******************************************************************
class MyRenderer:
public QObject,
public QQuickFramebufferObject::Renderer,
protected QOpenGLFunctions
{
Q_OBJECT
public:
virtual void render();
private:
static void RequestGameChanges();
};
void MyRenderer::render() {
if ( !m_Initialized ) {
QOpenGLFramebufferObject *theFbo = this->framebufferObject();
InitializeGl( theFbo ); // Not shown
m_MyGame = &MyGame::Create();
m_MyGame->RegisterCallback(
reinterpret_cast<qml_Function>(MyRenderer::RequestGameChanges)
);
m_Initialized = true;
}
m_MyGame->RestoreState();
m_MyGame->Redraw();
m_MyGame->SaveState();
m_PluginItem->window()->resetOpenGLState();
// Tell QML that we want to render again as soon as possible
update();
}
// This gets invoked in the middle of m_MyGame->Redraw()
void MyRenderer::RequestGameChanges() {
emit m_PluginItem->timeToMakeChanges();
}
// ******************************************************************
MyPlugin::MyPlugin() {
setMirrorVertically(true);
connect(
this, SIGNAL(windowChanged(QQuickWindow*)),
this, SLOT(HandleWindowChanged(QQuickWindow*))
);
}
void MyPlugin::HandleWindowChanged(QQuickWindow *inWindow) {
inWindow->setClearBeforeRendering(false);
}
void MyPlugin::makeChanges(QVariant inValue) {
MyGame *theGame = GetGame();
// Send the requested changes to theGame
}
QQuickFramebufferObject::Renderer* MyPlugin::createRenderer() const {
m_Renderer = new MyRenderer( *this );
}
MyApp.qml
import MyPlugin 1.0
Window {
MyPlugin {
property var queuedUpChanges: ([])
onSomeOtherSignal: queueUpChangesToMake();
onTimeToMakeChanges: makeChanges( queuedUpChanges );
}
Canvas { id:hack }
Timer {
interval:10; running:true; repeat:true
onTriggered: hack.changeWhatYouShow();
}
}
Bonus Points
The main question is "How do I modify my code so that I get 60Hz updates?" However, as seen in the QML, the setup above requires me to queue up all changes in QML so that they are able to be applied during the right spot in the MyGame::Render().
Ideally, I'd prefer to write QML without timeToMakeChanges, like:
MyPlugin {
onSomeOtherSignal: makeChanges( ... );
}
If there's a way to accomplish this (other than queuing up the changes in C++ instead)—perhaps something related to synchronize() I'd love to know about it.
I'd make a timer in QML that calls the makeChanges regularly. But store all the state in MyPlugin. Then, in Renderer::synchronize(), copy from MyPlugin to MyRenderer, so it can be used by the MyGame.
(although, I wouldn't do any gamelogic-related calculations in QML ever in the first place)

How to get stuff to show up in my window?

I've been playing with OpenGL. I'm confused because most commands seem to call a static method instead of the window object I create - by what arcane methods does the compiler divine my target window, I can't fathom.
I assume I've misunderstood something along the way, since I can't get my code to work. The snippet below produces a window with a transparent background, as opposed to a black background; trying a few other commands for drawing also gave me nothing. What am I doing wrong?
public static void Main()
{
using (OpenTK.GameWindow a = new OpenTK.GameWindow(800, 600, GraphicsMode.Default, "Sandboxy"))
{
a.Run(30);
OpenTK.Graphics.OpenGL.GL.ClearColor(0, 0, 0, 0);
OpenTK.Graphics.OpenGL.GL.ClearDepth(1.0);
OpenTK.Graphics.OpenGL.GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
}
}
Yes, you're definitely doing something wrong, but firstly, the static method thing.
The way it knows where to draw the stuff to, even though you're using static methods, is because OpenTK tells OpenGL (OpenTK.Graphics.OpenGL.GL) where to draw to when it creates the GameWindow, it binds the window to the static OpenGL context (on windows it does this through the Win32 functions wglCreateContext(HDC) and wglMakeCurrent(HDC, HGLRC), look those up if you want more information).
The reason it doesn't work, is because you try to clear everything after you start the render loop:
a.Run(30);
Doesn't just open the window, it also enters the render loop, meaning it will return only when the windows closes. This is quite obviously not what you want. You want to render in the loop, not afterwards.
The preferred way to draw it (for OpenTK) is create a class deriving from GameWindow, and overriding the functions to do with the loop:
class MyGameWindow : GameWindow
{
public MyGameWindow() : base(800, 600, GraphicsMode.Default, "Sandboxy")
{
}
protected override void OnRenderFrame(FrameEventArgs e)
{
GL.ClearColor(0, 0, 0, 0);
GL.ClearDepth(1.0);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
this.SwapBuffers();
}
public static void Main(string[] args)
{
using (GameWindow a = new MyGameWindow())
{
a.Run(30);
}
}
}
OpenGL commands operate on the current GL context. You acquire GL contexts from the operating system and make them current in a given thread via an OS-specific (wgl, glx, etc.) *MakeCurrent() call.

Pass argument to callback function COCOS2D Android

I've started working with cocos2d few days ago...and im working on small 2d game.
I figured out how to animate sprites. Now when sprite finished with animation I want it to be cleared from screen.
How to pass argument to callback function?
target.runAction(CCSequence.actions(repeatAnimation,
CCCallFuncND.action(this, "deleteTarget",target)));
Function is defined as:
public void deleteTarget(Object target)
It always gives me "NoSuchMethodException"...any idea?
Do it like this
CCCallFuncN ccfun = CCCallFuncN.action(this, "test");
public void test(Object sender) {
Do whatever you require
}

C++ / SDL encapsulation design help

So I am semi-new to C++, and completely new to SDL. Most of my conceptual knowledge of OOP comes from Java and PHP. So bear with me.
I am trying to work out some simple design logic with my program / soon to be side-scroller. My problem lies with trying to make my 'screen' layer (screen = SDL_SetVideoMode(...)) accessible to all my other classes; Hero class, background layer, enemies, etc. I have been loosely following some more procedural tutorials, and have been trying to adapt them to a more object oriented approach. Here is a little bit of what I have so far:
main.cpp
#include "Game.h"
#include "Hero.h"
int main(int argc, char* argv[])
{
//Init Game
Game Game;
//Load hero
Hero Hero(Game.screen);
//While game is running
while(Game.runningState())
{
//Handle Window and Hero inputs
Game.Input();
Hero.userInput();
//Draw
Game.DrawBackground();
Hero.drawHero();
//Update
Game.Update();
}
//Clean up
Game.Clean();
return 0;
}
As you can see, I have a Game class, and a Hero class. The Game class is responsible for setting up the initial window, and placing a background. It also updates the screen as you can see.
Now, since my Game class holds the 'screen' property, which is a handle for SDL_SetVideoMode, I am stuck passing this into any other class (ex: Hero Hero(Game.screen);) that needs to update to this screen... say via SDL_BlitSurface.
Now, this works, however I am getting the idea there has GOT to be a more elegant approach. Like possibly keeping that screen handler on the global scope (if possible)?
TLDR / Simple version: What is the best way to go about making my window / screen handler accessible to all my subsequent classes?
I like the way you are doing it.
Though rather than passing the screen reference I would pass a reference to a game itself. Thus each hero object knows which game it belongs too, it can then ask the game object for the screen as required.
The reason I would do this is so that in a few years when your game is a wide and successful product and you convert it for online-play you really need to do no work. The game server will be able to easily support multiple game objects, each game object hosting multiple hero objects. As each hero object wants to draw it asks the game for the screen abd updates the screen (the screen can now very from game object to game object and still work perfectly (as long as they have the same interface).
class Game
{
public:
Game(Screen& screen)
: screen(screen)
{}
virtual ~Game() {}
virtual Screen& screen() { return theGameScreen;}
void update() { /* Draw Screen. Then draw all the heros */ }
private:
friend Hero::Hero(Game&);
friend Hero::~Hero();
void addHero(Hero& newHero) {herosInGame.push_back(&newHero);}
void delHero(Hero& newHeor) {/* Delete Hero from herosInGame */}
// Implementation detail about how a game stores a screen
// I do not have enough context only that a Game should have one
// So theoretically:
Screen& theGameScreen;
std::vector<Hero*> herosInGame;
};
class Hero
{
public:
Hero(Game& game)
: game(game)
{game.addHero(*this);}
virtual ~Hero()
{game.delHero(*this);}
virtual void Draw(Screen& screen) {/* Draw a hero on the screen */}
private:
Game& game;
};
Main.
#include "Game.h"
#include "Hero.h"
int main(int argc, char* argv[])
{
//Init Game
Screen aScreenObject
Game game(aScreenObject);
//Load hero
Hero hero(game); // or create one hero object for each player
//While game is running
while(game.runningState())
{
//Handle Window and Hero inputs
Game.Input();
Hero.userInput();
//Update
Game.update();
}
//Clean up
// Game.Clean(); Don't do this
// This is what the destructor is for.
}
I don't know if it's elegant, but what I do for the side-scrolling game I'm making is to make a show() function in each class than draws to the screen, and passing the screen handle as a parameter. Then whenever I want to draw something to the screen I just do foo.show(screen). The screen handle is in main().
The first, and honestly, easiest solution, is to use a global variable. Yes, yes, yes, everyone says global variables are horrible, but in this situation, it's perfectly fine.
The other solution, which is a bit more work, but can result in somewhat more portable code, is to encapsulate your drawing functions into a single, static class. This way, you can draw to the screen directly without having to pass around a variable, or have to lie awake at night thinking the code review police will get you because you used a global variable. Plus, this can potentially make it easier if you ever decide to port your game to a new library. Some quick and dirty pseudocode:
class Drawing
public:
static void Draw(x, y, sdl_surface graphic, sdl_rect & clip=null);
static void init(sdl_surface & screen);
private:
sdl_surface screen;
void Drawing::Draw(x, y, sdl_surface graphic, sdl_rect & clip=null)
{
sdl_blit(x, y, graphic, clip);
}
void Drawing::init(sdl_surface & screen)
{
this.screen=screen;
}
It sounds like you're looking for a way to implement the Singleton design pattern, where you would have a single Screen object. If you know you're only ever going to have a single Screen object it should work fine.
In this case you would implement a static method on the Game class:
class Game
{
public:
static Game *GetTheSceenObject();
private:
static Screen *theScreen; // details of initialisation ommitted
}
that would return a pointer to the single Screen object.
If there is a possibility that you'll end up using multiple SDL screens, though, it may be worth creating a Draw() method in your Hero class that is responsible for drawing the hero on each of the Screens managed by the Game class by iterating through a list provided by the Game class.
That functionality could be contained in the methods of a common DrawableThingy class that Hero and Enemy are derived from.
Passing Game.screen around is more OO (though it might be better to have a getter function) than having one instance of it that can be accessed from any class, because if you have one global version, you can't have more than one Game.screen at any one time.
However if you know you'll only ever need one in the entire lifetime of the program, you might consider making Game::Screen() a public static function in the Game class that returns a private static member screen. That way, anyone can call Game::Screen() and get the screen.
Example (assuming ScreenType is the type of screen and that you store a pointer to it):
class Game {
public:
static ScreenType* Screen() {
if (!screen)
screen = GetScreenType(args);
return screen;
}
}
private:
// if you don't already know:
// static means only one of this variable exists, *not* one per instance
// so there is only one no matter how many instances you make
// the same applies to static functions, which you don't need an instance to call
static ScreenType* screen;
};
// and somewhere in a .cpp file
ScreenType* Game::screen = NULL;
// and you use it like this
ScreenType* scr = Game::Screen();
// use scr

WPF World Editor for my DirectX game engine

I am working on a small game and game engine in C++ using DirectX. The purpose is educational & recreational.
My next goal is to build a simple world editor that uses the game engine. For this I will need to move the engine into a dll so it can be consumed by the game and/or by the editor. The world editor will be a stand-alone tool and not part of the game. The main purpose of the world editor will be to read in and display my (custom) scene file, and allow me to annotate/modify properties on world objects (meshes), clone objects, pick up and move objects about and drop them, scale objects, etc., and then save out the modified scene so it can later be read by the game.
It has been recommended that I use wxWidgets for the editor. A bit of research makes me feel that wxWidgets is a bit old and clunky, though I am sure very fine GUIs can be written using it. It's just a steep learning curve that I don't look forward to. I have gotten the samples to build and run, but it was a headache.
A little more research and I find that I can integrate DirectX into a WPF app using a D3DImage. I have done a little with WPF and do not find it too intimidating and there are plenty of good books available (there is only one old one for wxWidgets), as well as scads of information on the web. I have gotten the rotating triangle example working and it seemed pretty straightforward.
So my question is:
Will WPF allow me to build a decent little world editor app that re-uses my game engine?
My game engine currently uses RawInput for mouse and keyboard; how will this work with WPF?
How does WPF affect my message pump?
It looks like I will have to write a lot of functions (facade pattern?) to allow WPF to interact with my game engine. Is there an easy way to factor this out so it doesn't get compiled into the game?
Any other tips or ideas on how to proceed would be greatly appreciated!
Thank you.
You need to create a wrapper class that exposes certain functionality of your game.
For example. This function is in my c++ game engine editor wrapper.
extern "C" _declspec(dllexport) void SetPlayerPos(int id, const float x, const float y, const float z);
Then in your c# wpf application you can create a static class allowing you to use those functions
[DllImport(editorDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void SetPlayerPos(int id, float x, float y, float z);
You will have to have functions for your basic functionality of the game engine through the dll.
things like
EditorMain
RenderFrame / Update
DXShutdown
So then you can call editormain in your wpf app constructor
System.IntPtr hInstance = System.Runtime.InteropServices.Marshal.GetHINSTANCE(this.GetType().Module);
IntPtr hwnd = this.DisplayPanel.Handle;
NativeMethods.EditorMain(hInstance, IntPtr.Zero, hwnd, 1, this.DisplayPanel.Width, this.DisplayPanel.Height);
You will need to create a message filter class and initialize it in the constructor as well
m_messageFilter = new MessageHandler(this.Handle, this.DisplayPanel.Handle, this);
here's how your message filter class could look
public class MessageHandler : IMessageFilter
{
const int WM_LBUTTONDOWN = 0x0201;
const int WM_LBUTTONUP = 0x0202;
IntPtr m_formHandle;
IntPtr m_displayPanelHandle;
EngineDisplayForm m_parent;
public MessageHandler( IntPtr formHandle, IntPtr displayPanelHandle, EngineDisplayForm parent )
{
m_formHandle = formHandle;
m_displayPanelHandle = displayPanelHandle;
m_parent = parent;
}
public bool PreFilterMessage(ref Message m)
{
if (m.HWnd == m_displayPanelHandle || m.HWnd == m_formHandle)
{
switch (m.Msg)
{
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
{
NativeMethods.WndProc(m_displayPanelHandle, m.Msg, m.WParam.ToInt32(), m.LParam.ToInt32());
if (m.Msg == WM_LBUTTONUP)
{
m_parent.SelectActor();
}
return true;
}
}
}
return false;
}
public void Application_Idle(object sender, EventArgs e)
{
try
{
// Render the scene
NativeMethods.RenderFrame();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
for doing win forms and wpf interop look here
http://msdn.microsoft.com/en-us/library/ms742474.aspx