2016

2016 has certainly been an interesting year. If I could largely sum up what’s been going on with me this past year, I’d say God’s been giving me an increasing sense of the seriousness and importance of the Gospel of Jesus Christ in the lives of people (myself included).

So, without further ado, here’s a collection of some Bible verses that have really stuck out to me throughout the last year:

For I am not ashamed of the gospel, for it is the power of God for salvation to everyone who believes, to the Jew first and also to the Greek. For in it the righteousness of God is revealed from faith for faith, as it is written, “The righteous shall live by faith.” — Ro 1:16-17 (ESV)

There is therefore now no condemnation to those who are in Christ Jesus, who do not walk according to the flesh, but according to the Spirit. For the law of the Spirit of life in Christ Jesus has made me free from the law of sin and death. — Ro 8:1-2 (NKJV)

who desires all people to be saved and to come to the knowledge of the truth. For there is one God, and there is one mediator between God and men, the man Christ Jesus, who gave himself as a ransom for all, which is the testimony given at the proper time. — 1 Ti 2:4-6 (ESV)

The Lord is not slow to fulfill his promise as some count slowness, but is patient toward you, not wishing that any should perish, but that all should reach repentance. — 2 Pe 3:9 (ESV)

save others by snatching them out of the fire; to others show mercy with fear, hating even the garment stained by the flesh. — Jud 23 (ESV)

For I decided to know nothing among you except Jesus Christ and him crucified. — 1 Co 2:2 (ESV)

For to me to live is Christ, and to die is gain. — Php 1:21 (ESV)

I appeal to you therefore, brothers, by the mercies of God, to present your bodies as a living sacrifice, holy and acceptable to God, which is your spiritual worship. Do not be conformed to this world, but be transformed by the renewal of your mind, that by testing you may discern what is the will of God, what is good and acceptable and perfect. — Ro 12:1-2 (ESV)

Finally, brothers, whatever is true, whatever is honorable, whatever is just, whatever is pure, whatever is lovely, whatever is commendable, if there is any excellence, if there is anything worthy of praise, think about these things. — Php 4:8 (ESV)

We demolish arguments and every pretension that sets itself up against the knowledge of God, and we take captive every thought to make it obedient to Christ. — 2 Co 10:5 (NIV)

For by the grace given to me I say to everyone among you not to think of himself more highly than he ought to think, but to think with sober judgment, each according to the measure of faith that God has assigned. — Ro 12:3 (ESV)

Not that we are competent of ourselves to claim anything as coming from us; our competence is from God, who has made us competent to be ministers of a new covenant, not of letter but of spirit; for the letter kills, but the Spirit gives life. — 2 Co 3:5-6 (NRSV)

Let no corrupting talk come out of your mouths, but only such as is good for building up, as fits the occasion, that it may give grace to those who hear. — Eph 4:29 (ESV)

You must understand this, my beloved: let everyone be quick to listen, slow to speak, slow to anger; for your anger does not produce God’s righteousness. Therefore rid yourselves of all sordidness and rank growth of wickedness, and welcome with meekness the implanted word that has the power to save your souls. — Jas 1:19-21 (NRSV)

I pray that, according to the riches of his glory, he may grant that you may be strengthened in your inner being with power through his Spirit, and that Christ may dwell in your hearts through faith, as you are being rooted and grounded in love. I pray that you may have the power to comprehend, with all the saints, what is the breadth and length and height and depth, and to know the love of Christ that surpasses knowledge, so that you may be filled with all the fullness of God.
Now to him who by the power at work within us is able to accomplish abundantly far more than all we can ask or imagine, to him be glory in the church and in Christ Jesus to all generations, forever and ever. Amen. — Eph 3:16-21 (NRSV)

do not be anxious about anything, but in everything by prayer and supplication with thanksgiving let your requests be made known to God. And the peace of God, which surpasses all understanding, will guard your hearts and your minds in Christ Jesus. — Php 4:6-7 (ESV)

And let the peace of Christ rule in your hearts, to which indeed you were called in one body. And be thankful. Let the word of Christ dwell in you richly, teaching and admonishing one another in all wisdom, singing psalms and hymns and spiritual songs, with thankfulness in your hearts to God. And whatever you do, in word or deed, do everything in the name of the Lord Jesus, giving thanks to God the Father through him. — Col 3:15-17 (ESV)

See that no one repays anyone evil for evil, but always seek to do good to one another and to everyone. Rejoice always, pray without ceasing, give thanks in all circumstances; for this is the will of God in Christ Jesus for you. Do not quench the Spirit. Do not despise prophecies, but test everything; hold fast what is good. Abstain from every form of evil.
Now may the God of peace himself sanctify you completely, and may your whole spirit and soul and body be kept blameless at the coming of our Lord Jesus Christ. He who calls you is faithful; he will surely do it. — 1 Th 5:15-24 (ESV)

Now faith is the assurance of things hoped for, the conviction of things not seen. — Heb 11:1 (ESV)

in hope of eternal life, which God, who never lies, promised before the ages began — Tt 1:2 (ESV)

Every good gift and every perfect gift is from above, coming down from the Father of lights, with whom there is no variation or shadow due to change. — Jas 1:17 (ESV)

Being confident of this very thing, that he which hath begun a good work in you will perform it until the day of Jesus Christ: — Php 1:6 (KJV)

Let us hold fast the confession of our hope without wavering, for he who promised is faithful. — Heb 10:23 (ESV)

Therefore, since we are receiving a kingdom that cannot be shaken, let us give thanks, by which we offer to God an acceptable worship with reverence and awe; — Heb 12:28 (NRSV)

Now to him who is able to keep you from stumbling and to present you blameless before the presence of his glory with great joy, to the only God, our Savior, through Jesus Christ our Lord, be glory, majesty, dominion, and authority, before all time and now and forever. Amen. — Jud 24-25 (ESV)

But each person is tempted when he is lured and enticed by his own desire. Then desire when it has conceived gives birth to sin, and sin when it is fully grown brings forth death. — Jas 1:14-15 (ESV)

Religion that is pure and undefiled before God, the Father, is this: to care for orphans and widows in their distress, and to keep oneself unstained by the world. — Jas 1:27 (NRSV)

If a brother or sister is poorly clothed and lacking in daily food, and one of you says to them, “Go in peace, be warmed and filled,” without giving them the things needed for the body, what good is that? — Jas 2:15-16 (ESV)

So whoever knows the right thing to do and fails to do it, for him it is sin. — Jas 4:17 (ESV)

By this is love perfected with us, so that we may have confidence for the day of judgment, because as he is so also are we in this world. There is no fear in love, but perfect love casts out fear. For fear has to do with punishment, and whoever fears has not been perfected in love. — 1 Jn 4:17-18 (ESV)

We love because he first loved us. — 1 Jn 4:19 (ESV)

Those whom I love, I reprove and discipline, so be zealous and repent. Behold, I stand at the door and knock. If anyone hears my voice and opens the door, I will come in to him and eat with him, and he with me. — Re 3:19-20 (ESV)

and how from childhood you have been acquainted with the sacred writings, which are able to make you wise for salvation through faith in Christ Jesus. All Scripture is breathed out by God and profitable for teaching, for reproof, for correction, and for training in righteousness, that the man of God may be complete, equipped for every good work. — 2 Ti 3:15-17 (ESV)

who forbid marriage and require abstinence from foods that God created to be received with thanksgiving by those who believe and know the truth. For everything created by God is good, and nothing is to be rejected if it is received with thanksgiving, for it is made holy by the word of God and prayer. — 1 Ti 4:3-5 (ESV)

Keep your lives free from the love of money, and be content with what you have; for he has said, “I will never leave you or forsake you.” So we can say with confidence,
“The Lord is my helper;
I will not be afraid.
What can anyone do to me?” — Heb 13:5-6 (NRSV)

For we are his workmanship, created in Christ Jesus for good works, which God prepared beforehand, that we should walk in them. — Eph 2:10 (ESV)

And let us consider how to stir up one another to love and good works, not neglecting to meet together, as is the habit of some, but encouraging one another, and all the more as you see the Day drawing near. — Heb 10:24-25 (ESV)

And now, little children, abide in him; that, when he shall appear, we may have confidence, and not be ashamed before him at his coming. — 1 Jn 2:28 (KJV)

Then I saw a new heaven and a new earth, for the first heaven and the first earth had passed away, and the sea was no more. And I saw the holy city, new Jerusalem, coming down out of heaven from God, prepared as a bride adorned for her husband. And I heard a loud voice from the throne saying, “Behold, the dwelling place of God is with man. He will dwell with them, and they will be his people, and God himself will be with them as their God. He will wipe away every tear from their eyes, and death shall be no more, neither shall there be mourning, nor crying, nor pain anymore, for the former things have passed away.”
And he who was seated on the throne said, “Behold, I am making all things new.” Also he said, “Write this down, for these words are trustworthy and true.” — Re 21:1-5 (ESV)

And I saw no temple in the city, for its temple is the Lord God the Almighty and the Lamb. And the city has no need of sun or moon to shine on it, for the glory of God gives it light, and its lamp is the Lamb. — Re 21:22-23 (ESV)


Scripture quotations marked (ESV) are from The Holy Bible, English Standard Version®, copyright © 2016 by Crossway Bibles, a division of Good News Publishers. Used by permission. All rights reserved.

Scripture quotations marked (NIV) are taken from The Holy Bible, New International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica, Inc.™Used by permission. All rights reserved worldwide.

The Scripture quotations contained herein and marked (NRSV) are from the New Revised Standard Version Bible, Copyright © 1989, Division of Christian Education of the National Council of the Churches of Christ in the U.S.A., and are used by permission. All rights reserved.

Scripture quotations marked (NKJV) are taken from the New King James Version.
Copyright 1979, 1980, 1982 by Thomas Nelson, inc.
Used by permission. All rights reserved.

Scripture quotations marked (KJV) are from the King James Version, which is in the public domain.

On C++ Build Systems

I’ve been thinking about C++ build systems a lot recently.  I like programming in C++ a lot (relatively speaking), but I don’t think it’s news to anyone that the build system leaves a lot to be desired (dependency management, header + .cpp files, etc.).

It all started back when I started watching Handmade Hero.  Rather than using some complex build systems or even an IDE like Visual Studio, Casey Muratori just used a simple build.bat file to call the compiler.  I’m certainly no fan of batch as a language, but the simplicity of the build script along with the ease of understanding exactly how your program is compiled/linked were appealing.  He also basically just compiled 1 single .cpp file (which obviously simplifies things) – often called a “unity” or “single translation unit” build.

The next major piece came when watching videos for Jonathan Blow’s new “Jai” language.  One critical point Jon makes is that we probably should be writing our build scripts in the language we’re programming in – why bother learning some other (and often inferior) language just to build your program?

There is one point where I differ from Jon and Casey – I actually like using Visual Studio a lot.  I don’t necessarily like everything about it (notably the project files), but on the whole, I feel like the Visual Studio IDE makes me more productive compared to other alternative I’ve tried.

Anyway, it’s probably going to be some time before “Jai” or another language supplants C++.  So I was wondering…why not try and get most of the benefits mentioned above in C++?

Goals

Before we go any further, let me explicitly state some of the goals for my idea for a better C++ build system/IDE integration:

  • Build via the command line with minimal options to remember.
  • Build via Visual Studio.
  • Not specify a bunch of files when building.
  • Easily understand exactly how a program is built.
  • Easily tweak how a program is built.
  • Minimize dependencies on non-native tools (outside of the language, operating system, and Visual Studio).
  • Not manually manage Visual Studio solution, project, etc. files.
  • Easily find all files for a project within Visual Studio.
  • Edit files within Visual Studio.
  • Debug within Visual Studio.
  • Simplicity.

Prior to work put in for this blog post, I played around some with the build.bat and unity build ideas, both from the command line and within Visual Studio (generating solution/project files manually using the IDE).

The Build Script

From the above, the simplest idea for meeting the “build” requirements is the build.bat idea.  Batch files are built into Windows, and the complexity needed to call the compiler isn’t so large that it drives me crazy using the batch language.

All we really need to do to generate such a build script is have a program write out a basic text file, with a few possible parameters tweaked.  Very simple – the text could be easily embedded as strings in a program.

The basic build.bat file Casey Muratori created for Handmade Hero can be used as a starting point.  On tweak I might like to make (haven’t fully settled on this yet) is automatically calling the VCVARSALL batch file in the build script – that way, I don’t have to worry about making sure the appropriate settings are always set.  Unfortunately, one downside to this from my experience is that sometimes you’ll get an error about a command/path being too long if you repeatedly run the build.bat file in the same command prompt Window.  I haven’t run into any problems with this in Visual Studio yet though.

Deciding exactly what compiler flags/settings or other parameters to include in the build.bat file is tricky.  I’m not sure exactly what I personally want yet, but it might be different from what Handmade Hero has.  For now, punting and just having a basic build script for building a debug build is fine.

I might want to actually wrap a lot of the options in the build script in a separate C++ program – that wouldn’t certainly make supporting advanced options/features easier.  Of course, that has the trade-off of being another program people would have to download/build.

On “Unity” Builds

Before moving on, just a few comments on “unity” or “single translation unit” builds.  They’re definitely an interesting idea, with a nice benefit of speeding up build times.

One thing I definitely like about the idea is that you only have to specify 1 file when passed to the compiler – no need to manually manage a bunch of them.

However, I’m not completely sold on the idea, as it sort of requires restructuring how you right code in an unconventional manner.  And while I have no concrete evidence for it, it seems like structuring code/builds this way might complicate re-use in large code bases where you want to use code across multiple projects.  I’d like to still write my code in a more “conventional” C++ way (many separate files, including the less-than-ideal header + .cpp files) to avoid risks in going all-in with a unity build.

How can we get around these conflicts?  Well, Jonathan Blow’s idea of specifying your build in your regular programming language provides some hints.  We can create a separate file that just #includes all of the .cpp files we want to compile – no need to write the rest of your code in an odd way.

This actually works pretty well from my testing, but it isn’t perfect.  In particular, I was hoping that this file with just a bunch of #includes could end with a file extension other than .cpp, but the Visual Studio compiler doesn’t seem to be able to compile files with other extensions (if you know a way around this, let me know).  The idea of not modifying your “other” .h/.cpp files almost may not be 100% feasible – from my testing, I’ve had to make a few modifications/re-order certain things – but the modifications have been relatively minimal so far to a point where it wouldn’t be much of a burden (or maybe no burden at all) if I wanted to return to a “conventional” C++ build model.

It might be nice to generate this .cpp file with just a bunch of #includes automatically one day, but there might be some challenges, and it’s certainly not at the top of my priority list.

Visual Studio Project Files

As mentioned above, I’ve manually created Visual Studio solution/project files for C++ projects using a build.bat + unity build approach.  But I don’t like having to manually add all files in my project or tweak various build settings.

How to solve this problem?  Well, for the most part, the Visual Studio solution/project files can basically just be copied, meaning that we can embed most of the text directly in a simple program.  There are some unique IDs in the files, but at least from my testing, re-using them doesn’t seem to be a problem.

What remains then?  Well, basically just getting a list of files/folders to include in the Visual Studio project and project filters files.  Recursively getting a list of files/folders in a directory…that doesn’t seem too hard, right?  While the Windows API for doing this isn’t super ideal in my opinion, it’s not too complicated.  So doing this should be pretty easy.

Let’s Do This…Well, Already Done…

I was planning to originally write this blog post before I went and tried to implement any of it.  But feeling extra motivated about this recently, I actually went and recently implemented a lot of the basics for what I want (as described above).  And it didn’t take that long – maybe around 3-5 hours total (at night after work).  Given a folder of code and using the quick program I wrote, I can automatically generate a Visual Studio solution/project and build.bat script that actually works (minus project-specific build tweaks).

It’s far from “complete” – I’ve only tested it on one specific project so far, the build.bat script is most definitely insufficient, and there aren’t a lot of options.  I’ll add improvements as I find I need them, but it’s “good enough” now to at least put out there.

The code is available here on GitHub.  I hope it will be helpful to some others out there.  If you have any suggestions, feel free to forward them to me.  Although, since I’m making the code itself public domain, you’re certainly more than welcome to make your own changes to suit your needs.

Software Estimation Resources

I’ve recently been looking to improve my software estimate/scheduling/management abilities. Below are a few resources that I’ve found helpful in one way or another:

This is largely intended to be a quick reference to things I might want to review at later times, so I’ll update it if I find anything new.

Game Audio Programming Resources

I’m not really musically inclined at all, and I recently did some basic audio programming work for the Noah’s Ark game that involved low-level audio samples and SFML.  Not sure what (if anything) might ultimately come out of that, but I did learn some things about audio within the context of game programming.  Some of my favorite resources that were helpful during this time are below:

Video

Books

Notes from Noah’s Ark Game Refactoring

Recently, I mostly finished a fairly large scale refactoring of code for the Noah’s Ark game.  I’m pretty pleased with how it turned out – the code seems simpler, and I think I’ll be able to more rapidly add features.

Part of the refactoring was motivated by some perceived complexity introduced by some architectural ideas I was trying out – namely, “entities”, “components”, and “systems” – that I’d roughly borrowed from other game engine designs that I’ve read about through the years.

Needless to say, those ideas didn’t seem to be working very well for the game I’m working on.  From various things I’ve learned over the last year, it seemed like there were better solutions to things I was dealing with that would allow replacing a lot of complexity with simplicity.

Will the game’s architecture ultimately return to code similar to what it looked like before the refactoring?  Maybe.  But for now, I think the code is in a much better state than it used to be.  Miscellaneous notes from the refactoring are below.

Making main() Meaningful

Originally, I had a very small amount of code in main():

int exitCode = NoahArkGame::RunGame();
return exitCode;

The bulk of the game logic was contained in a NoahArkGame class.  Part of this was a holdover from when I was using Haaf’s Game Engine before switching over to SFML, but even then, it was largely unnecessary.

So I eliminated this NoahArkGame class and basically moved its logic directly into main().  Why?  Well, using this class (along with some others – “state” and “system” classes) resulted in more indirection that was making things a bit harder to understand, force-fitting certain things into a structure that might not actually be appropriate.  Putting the core game logic in main() meant I could more clearly see the connections necessary between different parts of the code and would make it easier to modify as I discovered new things.

Another interesting idea is that many people often describe a program has having a “main loop.”  Well, if you’re someone new to a code base, where would you expect to find the code for the “main loop”?  Without introducing new constructs that someone would have to learn, the first obvious answer that comes to mind is main().  Anything else is introducing a layer of indirection that has to be jumped through.  I should note that I may not 100% agree with this philosophy, but at the very least, there’s nothing inherently bad about putting a lot of code for the Noah’s Ark game directly in main() for now.  Don’t be afraid of main().

One final note – putting logic directly in main() does have the downside of making it harder to unit test (not that I was planning to do so with the NoahArkGame class either).  But a lot of the pieces orchestrated by the main loop (i.e. actual user input, rendering to screen, etc.) are inherently harder to unit test anyway, so trying to “unit test” the could be a near futile effort anyway.  Just a valid trade-off to consider; there may be more effective ways to test the main loop than unit testing too.

Cleaning Up Tile Map Code

I had a ton of code/classes related to dealing with “tile maps” in the game.  Some of this was intentionally duplicated as I was refactoring smaller parts of the game, but even accounting for that, it was still a messy sea of complexity.

I ultimately eliminated several classes – OverworldMap, ScrollableOverworldMap, TileMapBuilder, TileMapObjectLayer, TileMapTileLayer, ITileMapData, ITileMapLayer, OverworldMapSpecification, SurroundingTileMapLoader, TileMapLayers, TileMapLoader, TiledMapJsonFile – that didn’t really have the best abstractions for useful and intuitive “real-world objects” (in the context of the problems of the game) and thus made the code as a whole more difficult to understand.  That left what seems like a more intuitive collection of classes.

A ton of code was also moved/removed from the TileMap class – it either wasn’t needed anymore or seemed better to place elsewhere for now (to avoid making the TileMap class harder to understand).   I should note that the name of the TileMap class may not best fit the abstraction that it represents, but it isn’t quite clear to me yet exactly what the best class name would be.

Loading All Assets At Startup

I was previously loading assets (i.e. tile map/image files) from disk on-demand, only when needed.  That resulted in some jitteryness/slowdowns during gameplay that required additional complexity to solve.

I did some calculations, and it seemed reasonable to fit basically all of my game assets in memory at once (i.e. 50-60 MB of total usage; my “personal limit” is to keep the game under 100 MB of usage).  Furthermore, most of the assets would be needed in memory basically for the entirety of gameplay anyway, so there isn’t going to be much of a reason to try and free up memory for them.

Therefore, I changed things to just load all assets into memory at startup.  This has the downside of taking about 6-8 seconds (it was 12-14 seconds before I added a tiny bit of multi-threading for tile map loading).  But I’m not too concerned about this since I think I can ultimately have most of this go on in the background during an intro sequence that will be added later.  The good news is that the rest of the code generally doesn’t have to worry about asset loading times.

Making Member Variables Public

Another significant change I made was to make most member variables public instead of private.  This is a common “no-no” in encapsulation/object-oriented guidelines, but I’ve been questioning it lately.

First off, nothing is truly “private” – all there really is is data in the computer’s memory.  Various programming languages do somewhat good jobs at trying to protect these private variables from external access, but this is often just a compilation error.  In C++, you can still easily access private members using pointer offsets.  And some languages don’t even properly support “private” member variables – everything is public, and you have to jump through extraordinary hoops to emulate privacy.

So privacy either doesn’t exist in some programming languages and can be subverted using [often bad] techniques in others.

What are the supposed benefits of private members?  Primarily, the intent seems to be to encapsulate/hide implementation details.  There’s certainly some value in that, but just because a piece of data can be thought of as a member of a class, that doesn’t necessarily mean it is an “implementation detail.”  Sometimes, a data member can intuitively be thought of as part of the abstraction presented by a class.  In these cases, it seems to make more sense for that data member to be public – users expect that data to be in the class by virtue of the abstraction it is trying to present.  Trying to hide this and provide public getter/setter methods just results in more code to read/write/maintain and often makes a class harder to use.

Furthermore, most of the “problems” I tend to see in code aren’t actually caused by lack of “private” members – they’re more fundamental design problems.  As code has to get more complex to solve more complex problems, the impact of a public/private member seems to get tinier in the context of these larger design issues.  And if we’re trusting our developers to solve these much more complicated problems, shouldn’t we be trusting them to make responsible decisions when it comes to data access?  In short, the usage of a data member is more of the issue rather than its public/private accessibility.  Good developers should be able to notice code that is potentially accessing a private implementation detail in a negative way and avoid that code entirely.  Rather than treating a symptom of the problem, I’m wondering if perhaps we should focus more on addressing what seems to be the root cause of these problems – mentorship and growth for programmers.  We want programmers to become better people, and not just so that they can craft simple yet exceptional software.

All of that said, I think there is still probably a case for using private members and having public member functions in public API design – you don’t want to cause frustration or unnecessary work for your users if you need to change some implementation detail or data representation.  But for “internal” code that you don’t intend to heavily reuse throughout tons of projects, I question the value of private members.  It’s your code, and you can change it however you see fit.  And if you do need to change something, the compiler (at least in languages like C++) can easily point you to all of the places that need to be changed.

Not Using Classes For Everything

Last but not least, I deleted some classes that were just serving as cruft and making it harder to use/modify code.  In particular, the GraphicsSystem and CollisionSystem classes were eliminated, with the code now existing as free-floating functions in separate files.

I still find [at least what I consider] “object-oriented programming” to be valuable in certain places.  Primarily, allowing a human to work intuitively with “objects” he/she is familiar with is powerful for solving certain kinds of problems.  Classes can also provide a nice home for functionality that can make it easier to find code in a large code base.

However, object-oriented programming certainly is not a silver bullet.  Not every concept is necessarily best represented as an object.  Too many classes can make a code base harder to navigate.  And object-oriented programming can result in too much indirection and structure that could make code harder to understand or change (which can be costly if an object-oriented design is flawed).

Might the free-floating functions eventually end up in a class?  Perhaps.  If I can find a good home for them eventually, that’s something I’d kind of like to do.  But I don’t yet know what that home would be, and right now, free-floating functions makes it easier for me to shape the code into a proper design later.

 

Anyway, that sums up a lot of the major changes I recently made for refactoring code for the Noah’s Ark game (and why).  It’s entirely possible that something I’ve mentioned above is horribly wrong or stupid.  Time will tell, but I think the code is better now than it was before.

Happy coding.

Mini Book Review: Design Patterns Explained

I recently finished reading Design Patterns Explained.  I’m not really going to do a full review of the book, but there were some helpful parts that seemed worth pointing out.

In general, most of the book didn’t seem all that useful.  In particular, the chapters focusing on specific design patterns were the least appealing.  I can see situations where the general approach of a design pattern might be applicable, but specifics of a particular problem at hand likely would dictate a simpler variation of the pattern that could be derived without needing to specifically think about patterns.

However, there were two particular chapters that I liked a lot and thought were really valuable.

The first is chapter 8 “Expanding Our Horizons”.  There is lots of good discussion in this chapter, but the diagram showing how commonality and variability analysis relate to conceptual, specification, and implementation perspectives was a big highlight.  Thinking about a problem from the “conceptual” perspective helps me stay more focused in the problem domain when programming, and the other two perspectives help bridge the gap between the problem domain and crafting solid code.

The next useful chapter was chapter 16 “The Analysis Matrix”.  Extending the ideas behind commonality and variability analysis, this chapter describes a practical, concrete tool that can easily be used to more clearly see commonalities and variations within a problem.  One particular benefit of this approach that I like is that I think it can be helpful to make sure you don’t overdesign flexibility into your program – the variations you actually need are right there in the matrix (table).

There are other chapters in the book that may be useful.  However, most of the topics they cover were covered in the two chapters outlined above, and those two chapters do a great and better job of explaining the topics.

So while most of Design Patterns Explained didn’t seem too useful to me, I highly recommend checking out the two chapters mentioned above if you get the chance.  Definitely at least worth contemplating to see if they might be useful in certain situations.

Handmade Hero and a New Programming Language?

Relatively recently, I found and started watching the Handmade Hero series.  In the series, Casey Muratori is basically coding a complex game from scratch (i.e. using no libraries beyond what is required by an operating system).  You can read more by following the link above.

I’m far behind (and probably will never catch up) due to limited time, but it’s been a great series.  While I have different opinions on some things Casey brings up (and certain items may only apply to different types of software), there is no doubt that he knows his stuff and is far more experienced than me.  I’ve learned some neat tricks from watching, and he has encouraged me to think more critically about certain aspects of programming.  If you’re interested in learning lowish-level programming in a language like C, I highly recommend checking it out.

Watching Handmade Hero also led me to find Jonathan Blow’s videos where he talks about a potential new programming language for games.  His insight into flaws in current programming languages and proposals to fix some of these issues were fascinating, and Jonathan even has a prototype compiler for his new language that seems to work pretty darn well.  I’m looking forward to seeing that new language progress.

Anyway, just wanted to say thanks to both of these guys.  If those topics seem interesting to you, I recommend looking into their programming video series.  Lots of neat learning opportunities.

 

God Loves You

A lot of this blog will probably cover programming/game development, but today I’m writing about a much more important topic: God and his love and desires for us.

God created everything (Genesis 1-2, John 1:3), including us (individual human beings).  That in and of itself is amazing, especially when you think about the harmony that exists to make the universe actually work.

Unfortunately, we sinned (Genesis 3,  Romans 3:23).  The natural consequence of this sin is death (Romans 6:23).  Despite this rebellion against God and his intended design for us, he has continued to pursue us throughout the history of the Israelites and into today.

In fact, God even came to earth as the man Jesus Christ (John 1:14).  Why did he come to earth?  To give us abundant life:

The thief cometh not, but for to steal, and to kill, and to destroy: I am come that they might have life, and that they might have it more abundantly.

John 10:10 (KJV)

Why did he want to come to earth?  He loves us and doesn’t want us to die:

For God so loved the world, that he gave his only begotten Son, that whosoever believeth in him should not perish, but have everlasting life.

John 3:16 (KJV)

Christ died on the cross even while we were still sinners (Romans 5:8), giving us forgiveness of sins (Matthew 26:28).  His resurrection gives us birth into a new life (1 Peter 1:3).

That does not mean that life will be easy, but it does mean that we can go through it with the overcomer (John 16:33) and experience eternity with him.  And it is good news that nothing can separate us from that (Romans 8:38-39).

Isn’t it wonderful how we can have a relationship with the perfect and loving Creator?  God desires for you to have the best life possible, from now and into eternity.  If you do not know God through Jesus Christ, I encourage you to seek him, and feel free to contact me for questions or discussion.  There is no condemnation in Christ Jesus (Romans 8:1, John 8:11), but he does call us to repent from our sins (Luke 5:32).

Posted in God.

I Made a Model

I recently began digging deeper into learning 3D modeling.  I studied 3D computer graphics a decent amount in school.  However, this study was focused more on the programming-side of things.  I never really got a ton of exposure to the “end user” side of things.  This seemed to be holding me back from creating any type of 3D software that would truly be useful to end users, so I’m working to gain a better understanding of the 3D art process.

I’m using Blender because its free and fairly sophisticated.  I tried some “simpler” free 3D modeling products, but they didn’t quite do it for me.  It felt like something was missing.  The tutorials here and videos from Chris DeLeon were very helpful in getting me started.  They didn’t necessarily touch on what I’m more interested in modeling (fun little characters or other small objects) but were still helpful.

As I went through some of those tutorials, something finally “clicked” that hadn’t in my previous attempts at 3D modeling: 3D modeling really is like modeling with real-life clay (or Play-Doh).  Given a very basic shape, it is up to you to mold and transform it into what you desire.  In retrospect, this seems obvious but didn’t click with me until recently.

Anyway, I finally made my first 3D model on my own:

BreadModel_08_24_2014

Tada!  It is supposed to be a slice of bread with eyeballs and a mouth.  Originally, I was going to make a full cartoony sandwich, but after making just one slice of bread, it seemed better to scale back and do something simpler.

The above bread slice started out as a cube, which was resized to make the thinner slice of bread.  After that, almost all of the changes done were created using the Knife tool, which allows cutting into a mesh to create new edges (left hand side in my Blender setup):

BlenderMeshAddTools

The Knife tool was used to cut away the edges of the bread to make things look rounded.  From there, I just deleted/moved edges of the mesh as needed.  Occasionally, I also had to create a face since deleting edges sometimes removed a face:

BlenderMakeFace

The mouth was created using a combination of the Knife and Extrude tools.  The eyeballs are just spheres moved into the slice of bread, and the pupils are just really short cylinders moved on top of the eyeballs.

I should note that nothing about this model is necessarily symmetrical – cutting the mesh on each side was done individually.  I believe there is a way to have Blender automatically mirror changes on a model to make things symmetrical – I just need to figure out how.  Working more efficiently is definitely something to learn over time, but getting a basic model “done” with whatever tools seemed obvious was a pleasant start for me.

My next steps are going to be to see what else I can do to this model (texturing, etc.) to make it look good, which should also provide more learning opportunities.  If any more experienced artists have any tips, feel free to leave them in the comments.  I’m definitely still a “newbie” when it comes to 3D art.

 

Fixing Memory Usage Issue for Noah’s Ark

I recently ran into a memory usage defect for my Noah’s Ark game. Basically, as the player scrolled to different tile maps in the overworld, memory usage would continue to climb, eventually bringing the game to a crawl. The fix was really simple but involved some more subtleties of C++ smart pointers, so it seemed worth writing about.

Graphics Management
First, it is important to understand how graphics are currently managed in the game code. Different types of graphics components are created from the GraphicsSystem. The GraphicsSystem is then responsible for rendering all of the graphics on screen.

I’m not necessarily sure this is the “best design” for the game (if you have other ideas, feel free to suggest them!). It is just something I’m experimenting with from various things I’ve read (mostly on entity component systems or ways to avoid having all of my game objects have explicit render methods). My main goal was to be able to easily apply global settings to all of the rendered graphics without having to touch a bunch of classes. Time will tell how well this works out.

Map Scrolling
The second major piece of the puzzle is to understand how the game scrolls between individual tile maps in the overworld. At any given time, the OverworldMap holds the current, top, bottom, left, and right TileMaps (assuming they exist):

The tile maps in memory at any given time in the Noah's Ark game.

When the player reaches the edge of the current map, the game scrolls to the appropriate adjacent map (if one exists), and then reloads any new maps surrounding this new map being scrolled to.

The Bug
There is a bit of a problem with the above approach, if you look at the details of the specific data types used. The graphics components created by the GraphicsSystem are returned as shared_ptrs and were (before the fix) also being stored as shared_ptrs in the GraphicsSystem class. These shared_ptrs are then used by whatever objects the graphics are for. In this case, these shared_ptrs were also used by Tiles in the TileMap class.

When scrolling to new TileMaps, the old TileMaps would be destructed, decrementing the reference counts for the shared_ptrs for Tiles in the map. However, since the GraphicsSystem still stored these shared_ptrs for the tile graphics, the reference count would still be 1, so the tile graphics would persist in memory. New maps would be loaded, creating new tile graphics components, but all of the old tiles would still exist. Obviously, this is problematic and leads to increasing memory usage over time, which ended up slowing the game to a crawl.

The Solution
I actually was aware of this problem during original implementation of the design outlined above but forgot about it by the time the defect actually manifested itself. This was a pretty major architecture problem, but I didn’t want to abandon the idea of having a centralized place (away from the main game objects) to control rendering.

I couldn’t use unique_ptrs since the graphics components needed to be accessible by both the GraphicsSystem and the individual objects the graphics are for. There are ways around this, such as using raw pointers, but that would make communicating when the resources were to be deleted from the GraphicsSystem pretty ugly (I also don’t like the lack of clarity that raw pointers can present when reading code, but that is for another blog post).

Fortunately, C++ had an elegant solution. Enter the weak_ptr. The description on the linked page is best to read for an understanding (and examples help), but a weak_ptr allowed me to break the > 0 reference count problem described above in a pretty nice way.

When an object like a Tile (part of a TileMap) is destructed, I wanted it to communicate to the GraphicsSystem that the graphics for the Tile could be deleted. To accomplish this, I made the following changes:

The GraphicsSystem was changed to store its graphics components as weak_ptrs instead of shared_ptrs:

std::list< std::weak_ptr<IGraphicsComponent> > m_graphicsComponents;

One nice thing is that the weak_ptr class has a constructor that allows it to be constructed from a shared_ptr, meaning I didn’t have to touch the code that added items to the above container.

Next, I had to update the for loops that iterated over the graphics components to use weak_ptrs instead of shared_ptrs. Before updating/rendering an individual graphics component, I needed to check if the object had already been deleted elsewhere (i.e. the Tile destructor) using the expired method:

if (!graphicsComponentWeakReference.expired())

(See the Wikipedia page for an overview of the concept of weak references.)

Assuming that the weak_ptr hasn’t expired, then the lock method can be called to obtain a usable shared_ptr to the object:

std::shared_ptr<IGraphicsComponent> graphicsComponent = graphicsComponentWeakReference.lock();

Tada! We’re almost done. The above code allows for checking if a graphics component has been deleted elsewhere, but it doesn’t actually solve the problem of increasing memory usage. The weak_ptrs are still stored in the list, so they need to be removed at some point. Fortunately, the list container has a remove_if that allows us to easily remove elements from the container that meet a certain condition (without resorting to the erase-remove idiom). Removing the expired graphics components can be done in what is effectively a single line of code:

m_graphicsComponents.remove_if([](std::weak_ptr<IGraphicsComponent>& graphicsComponent) { return graphicsComponent.expired(); });

That’s it! You can browse the full set of changes for this fix here. Finding and fixing this bug was a good learning experience for me, so hopefully it will be of use to some of you.