Jump to content

A Look at C++11 Shared Pointers in Leadwerks 5

Josh

1,459 views

C++11 introduces shared pointers, a powerful language feature that provides easy memory management without the overhead of garbage collection.  The example below should look familiar to you:

#include "Leadwerks.h"

using namespace Leadwerks;

int main(int argc, const char *argv[])
{
	shared_ptr<Leadwerks::Window> window = Leadwerks::Window::Create();

	shared_ptr<Context> context = Context::Create(window);

	shared_ptr<World> world = World::Create();

	shared_ptr<Camera> camera = Camera::Create();
	camera->SetRotation(35, 0, 0);
	camera->Move(0, 0, -6);

	shared_ptr<Light> light = DirectionalLight::Create();
	light->SetRotation(35, 35, 0);

	shared_ptr<Model> model = Model::Box();
	model->SetColor(1.0, 0.0, 0.0);
	model->SetPosition(-4, 0, 0);

	while (true)
	{
		if (window->Closed() || window->KeyDown(Key::Escape)) return false;
		
		Leadwerks::Time::Update();
		world->Update();
		world->Render();
		context->Sync();
	}
  
	//Everything will get automatically deleted when we return from this function
	return 0;
}

Using the auto keyword simplifies everything (and it makes this code compatible with Leadwerks 4):

#include "Leadwerks.h"

using namespace Leadwerks;

int main(int argc, const char *argv[])
{
	auto window = Leadwerks::Window::Create();

	auto context = Context::Create(window);

	auto world = World::Create();

	auto camera = Camera::Create();
	camera->SetRotation(35, 0, 0);
	camera->Move(0, 0, -6);

	auto light = DirectionalLight::Create();
	light->SetRotation(35, 35, 0);

	auto model = Model::Box();
	model->SetColor(1.0, 0.0, 0.0);
	model->SetPosition(-4, 0, 0);
	
	while (true)
	{
		if (window->Closed() || window->KeyDown(Key::Escape)) return false;
		
		Leadwerks::Time::Update();
		world->Update();
		world->Render();
		context->Sync();
	}
  
  	//Everything will get automatically deleted when we return from this function
	return 0;
}

Now things get interesting.  This function would normally cause a horrible memory leak, but with shared pointers everything is fine:

void SaveTexture(shared_ptr<Texture> tex)
{
	auto bank = Bank::Create(tex->GetMipmapSize());
	tex->GetPixels(bank->buf);
	bank->Save("pixeldata.dat");
}

Yet shared pointers can still equal nullptr:

auto bank = Bank::Create();
bank.reset();
Debug::Assert(bank==nullptr);

You can even simply set a shared pointer to nullptr, and if that was the last pointer that referenced it, it gets deleted!

auto bank = Bank::Create();
bank = nullptr;// auto deletion here!

How to Delete an Entity
The code below will not delete the entity, because a shared pointer is still stored in the world.

auto entity = Pivot::Create();
entity = nullptr;

The entity must be have its world set to NULL, and the shared pointer must be set to NULL or go out of scope:

entity = Pivot::Create();
entity->SetWorld(nullptr);
entity = nullptr;

Children use a weak pointer to the parent, so they will not cause self-referencing.

Asset Management
You no longer have to worry about calling Release() when loading assets:

auto material = Material::Create();
auto texture = Texture::Load("mytex.tex");
material->SetTexture(texture);
texture = nullptr;

Unused assets will automatically be deleted if they go out of scope:

auto material = Material::Create();
auto texture = Texture::Load("mytex.tex");
material->SetTexture(texture);
texture = nullptr;
material = nullptr;

But if they are in use, they will be retained in memory:

auto material = Material::Create();
auto texture = Texture::Load("mytex.tex");
material->SetTexture(texture);
model->SetMaterial(material);
texture = nullptr;
material = nullptr;

In conclusion, shared pointers automate many of the tasks we have been doing manually with the Leadwerks reference counting system and the AddRef and Release commands.



5 Comments


Recommended Comments

This feature is going to make the Leadwerks 5 editor a lot easier to write.

Share this comment


Link to comment

I take it the above code examples means you've already started transitioning LE to shared pointers?

What happens if you call delete on a shared pointer? Will I also have to transition my code when migrating to LE 5.5?

Share this comment


Link to comment
13 minutes ago, martyj said:

I take it the above code examples means you've already started transitioning LE to shared pointers?

I am adding defines in the code so the Leadwerks 4 source can be compiled in both modes.  It's nowhere near functional, I just started experimenting with it.  The LEADWERKS_5 define will keep the v5 stuff from messing with the current version.

13 minutes ago, martyj said:

What happens if you call delete on a shared pointer? Will I also have to transition my code when migrating to LE 5.5?

They did a nice job with the implementation of this.  It looks like delete will just call the reset() function:
https://stackoverflow.com/questions/12321949/explicitly-deleting-a-shared-ptr

That means if this is the only handle to the object, the object will be deleted.  Otherwise, the shared pointer will just have its ref count decremented.  (In Leadwerks 4 you should be calling Release() on Leadwerks objects, not delete.)

Note that the Release() and AddRef() functions will not exist in Leadwerks 5.

Share this comment


Link to comment

This is optional right? We can still use the traditional method of assigning a type for each variable in our projects? 

I prefer the traditional way to be honest. Especially when developing multiplayer.

Share this comment


Link to comment
23 minutes ago, jen said:

This is optional right? We can still use the traditional method of assigning a type for each variable in our projects? 

I prefer the traditional way to be honest. Especially when developing multiplayer.

The type is a shared pointer (instead of a pointer).  The first example above shows how it is done.  I prefer the auto keyword because it is less to type.

Share this comment


Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Blog Entries

    • By Josh in Josh's Dev Blog 10
      Current generation graphics hardware only supports up to a 32-bit floating point depth buffer, and that isn't adequate for large-scale rendering because there isn't enough precision to make objects appear in the correct order and prevent z-fighting.

      After trying out a few different approaches I found that the best way to support large-scale rendering is to allow the user to create several cameras. The first camera should have a range of 0.1-1000 meters, the second would use the same near / far ratio and start where the first one left off, with a depth range of 1000-10,000 meters. Because the ratio of near to far ranges is what matters, not the actual distance, the numbers can get very big very fast. A third camera could be added with a range out to 100,000 kilometers!
      The trick is to set the new Camera::SetClearMode() command to make it so only the furthest-range camera clears the color buffer. Additional cameras clear the depth buffer and then render on top of the previous draw. You can use the new Camera::SetOrder() command to ensure that they are drawn in the order you want.
      auto camera1 = CreateCamera(world); camera1->SetRange(0.1,1000); camera1->SetClearMode(CLEAR_DEPTH); camera1->SetOrder(1); auto camera2 = CreateCamera(world); camera2->SetRange(1000,10000); camera2->SetClearMode(CLEAR_DEPTH); camera2->SetOrder(2); auto camera3 = CreateCamera(world); camera3->SetRange(10000,100000000); camera3->SetClearMode(CLEAR_COLOR | CLEAR_DEPTH); camera3->SetOrder(3); Using this technique I was able to render the Earth, sun, and moon to-scale. The three objects are actually sized correctly, at the correct distance. You can see that from Earth orbit the sun and moon appear roughly the same size. The sun is much bigger, but also much further away, so this is exactly what we would expect.

      You can also use these features to render several cameras in one pass to show different views. For example, we can create a rear-view mirror easily with a second camera:
      auto mirrorcam = CreateCamera(world); mirrorcam->SetParent(maincamera); mirrorcam->SetRotation(0,180,0); mirrorcam=>SetClearMode(CLEAR_COLOR | CLEAR_DEPTH); //Set the camera viewport to only render to a small rectangle at the top of the screen: mirrorcam->SetViewport(framebuffer->GetSize().x/2-200,10,400,50); This creates a "picture-in-picture" effect like what is shown in the image below:

      Want to render some 3D HUD elements on top of your scene? This can be done with an orthographic camera:
      auto uicam = CreateCamera(world); uicam=>SetClearMode(CLEAR_DEPTH); uicam->SetProjectionMode(PROJECTION_ORTHOGRAPHIC); This will make 3D elements appear on top of your scene without clearing the previous render result. You would probably want to move the UI camera far away from the scene so only your HUD elements appear in the last pass.
    • By tipforeveryone in tipforeveryone's Blog 12
      I spent a whole week for learning UE4 with cpp, yep, UE4 is a great engine for sure, but I found out that my mind could not understand the way UE4 works easily. It is too complex and made me tired. Then I returned to my Leadwerks project and felt so familiar. Soooo... sweet, everything is simple as it is
      It felt like I have had a long trip to UE city then return to my hometown. I miss Leadwerks indeed.
      Last year, I thought I could only use Leadwerks with LUA and never touch its CPP side. But I tried my best, learned Cpp for 8 months. Now I am not a cpp pro but I am confident in using this language. At least I can rewrite my whole project in CPP instead. this 3-years project helped me to understand my potential and interest in gamedev.
      I wish Josh be successful in progress of making Turbo, a new hope for much better Leadwerks.
      To all people who are using Leadwerks and help me these years, love you.
      ...
      Peace!
    • By Josh in Josh's Dev Blog 2
      Still a lot of things left to do. Now that I have very large-scale rendering working, people want to fill it up with very big terrains. A special system will be required to handle this, which adds another layer to the terrain system. Also, I want to resume work on the voxel GI system, as I feel these results are much better than the performance penalty of ray-tracing. There are a few odds and ends like AI navigation and cascaded shadow maps to finish up.
      I am planning to have the engine more or less finished in the spring, and begin work on the new editor. Our workflow isn't going to change much. The new editor is just going to be a more refined version of what we already have, although it is a complete new program written from scratch, this time in C++.
      It's kind of overwhelming but I have confidence in the whole direction and strategy of this new product.
×
×
  • Create New...