Sunday, August 28, 2016

Multi-Material Mesh Merge Snippet

For this video

public void AdvancedMerge()
 {
  // All our children (and us)
  MeshFilter[] filters = GetComponentsInChildren (false);

  // All the meshes in our children (just a big list)
  List materials = new List();
  MeshRenderer[] renderers = GetComponentsInChildren (false); // <-- you can optimize this
  foreach (MeshRenderer renderer in renderers)
  {
   if (renderer.transform == transform)
    continue;
   Material[] localMats = renderer.sharedMaterials;
   foreach (Material localMat in localMats)
    if (!materials.Contains (localMat))
     materials.Add (localMat);
  }

  // Each material will have a mesh for it.
  List submeshes = new List();
  foreach (Material material in materials)
  {
   // Make a combiner for each (sub)mesh that is mapped to the right material.
   List combiners = new List ();
   foreach (MeshFilter filter in filters)
   {
    if (filter.transform == transform) continue;
    // The filter doesn't know what materials are involved, get the renderer.
    MeshRenderer renderer = filter.GetComponent ();  // <-- (Easy optimization is possible here, give it a try!)
    if (renderer == null)
    {
     Debug.LogError (filter.name + " has no MeshRenderer");
     continue;
    }

    // Let's see if their materials are the one we want right now.
    Material[] localMaterials = renderer.sharedMaterials;
    for (int materialIndex = 0; materialIndex < localMaterials.Length; materialIndex++)
    {
     if (localMaterials [materialIndex] != material)
      continue;
     // This submesh is the material we're looking for right now.
     CombineInstance ci = new CombineInstance();
     ci.mesh = filter.sharedMesh;
     ci.subMeshIndex = materialIndex;
     ci.transform = Matrix4x4.identity;
     combiners.Add (ci);
    }
   }
   // Flatten into a single mesh.
   Mesh mesh = new Mesh ();
   mesh.CombineMeshes (combiners.ToArray(), true);
   submeshes.Add (mesh);
  }

  // The final mesh: combine all the material-specific meshes as independent submeshes.
  List finalCombiners = new List ();
  foreach (Mesh mesh in submeshes)
  {
   CombineInstance ci = new CombineInstance ();
   ci.mesh = mesh;
   ci.subMeshIndex = 0;
   ci.transform = Matrix4x4.identity;
   finalCombiners.Add (ci);
  }
  Mesh finalMesh = new Mesh();
  finalMesh.CombineMeshes (finalCombiners.ToArray(), false);
  myMeshFilter.sharedMesh = finalMesh;
  Debug.Log ("Final mesh has " + submeshes.Count + " materials.");
 }

Friday, August 19, 2016

World Weaving

In the past few days I've been writing a lot about getting players to engage with procedurally generated or tool-assisted worlds.

The basic idea is that you have to get the player to actually engage with the content. That's the idea of the mining/survival gameplay in most of these games: mining resources and shooting monsters involves engaging with the randomized hills, sprayed plants and rocks, random monsters, etc.

I posted a lot of tips about how to improve that engagement, but then I read this tweet and something became obvious: you can make players engage with your content in a much deeper way by making gameplay that pushes them along a specific physical path. IE, a golf course.

An open-world golf game. Randomly generated golf courses make up the world. You can wander the world as you like, and if you feel like playing a hole, you can. The structure of the world matters because you have to painstakingly cross that terrain to get from the tee to the hole. Every variation will be felt. Every plant that can get in the way, every animal that will chase your ball, every boulder with a tunnel through it.

There are some other things I can think of that work like this: hunting, hang-gliding, racing, even grand-scale base-building. But when I started to prototype these things, I found only the golf version felt right. Why?

Well, only the golf game had underlying structure. The racing, hunting, base-building stuff was a layer that gave context to the world, but the world itself still felt unstructured and arbitrary. On the other hand, the golf courses created a fundamental pattern that could be sussed out, and you could feel that there was a structure you could embrace or ignore.

After experimenting with the paper prototype a bit more, I realized that this was not just an illusion: creating the world out of crisscrossing golf courses was fundamentally creating a world with rigorous overlapping patterns. I created a world where the green of each hole is placed in a simple grid pattern, but the rest of the course goes off whichever way it wants, twisting and turning, until you place a tee wherever you end up. They cross each other wildly!

This can be played up even further by scaling the courses - these are minigolf, these are short holes, these are long holes, these are giant courses that you play in a mech. Even the generation is easy - you can just make every course a simple path edged with local debris (trees, rocks, sand), but have overlapping zones turned into hazards. So two courses crossing over each other have a sand pit or waterway in the middle.

As I expanded on this concept, I quickly found that I could tweak parameters and overlap rules and suddenly I had a planet with rivers and oceans (megamaid-size golf hazards), mountains and valleys (courses at different altitudes), and so on. Moreover, basic rules allowed me to place houses, cities, etc (wherever there are a number of tees near each other).

By using structured challenges in my procedural generation, I could weave those challenges together to generate a complex, meaningful world full of a variety of golf challenges.

...

Well, this isn't about golf.

This same idea can be extended. We can build a world out of crisscrossing race courses - some for high-speed drifting, some for off-roading, etc. We can build a world about hunting as long as we make "hunting paths" where the player stalks a target that is taking a specific path. We can make it about hang-gliding where we define expected launch positions and paths of descending height...

As long as we generate our world out of paths, we can weave them like a tapestry. They don't even need to be individually complex at all, because their overlaps create the complexity.

So... we can generate a world out of paths!

The player can choose which paths to engage with, but they'll be affected by (engage) nearby paths as well when they do. Moreover, even if they just wander, they'll see natural flow and charming obstacles!

Neat!

We can...

...

Hey, we don't have to build physical worlds.

What if we wanted to generate NPCs?

We have to drop the idea of "quests". Those are points, we need lines. So each NPC has a variety of "directions" they want to "go".

The obvious answer is stats: what if each NPC has an "arc" of stats they want? She wants to gain 20 armorsmithing points and then gain 15 strength. You need to build her up using the least number of resources (moves, political energy, days, cash, goodwill, whatever). Trying to build strength first would be "hitting into the rough", although if you could find a way to gain both at once that'd be fastest.

But the key to this whole affair is that the paths cross each other. Unless another NPC interacts with her stat growth along the way, there's not much depth to this.

I think there are a lot of ways to do this, but one way is to tie matching stats. She wants to increase armorsmithing from 10 to 30, but there are NPCs with armorsmithing of 19 and 23. So on her way up, she'll run into them and have to work around them - either by defeating them in armorsmithing, winning a seasonal competition, charming them, frightening them, or pushing their skill up to 30+ as well.

An extremely simple algorithm can "carry" these collisions along, so that these same people continue to engage her as they automatically try to raise their skill to higher than hers, which naturally creates events where she's pulled into conflicts with her own recurring set of rivals.

Moreover, it's very easy to simply allocate a new arc at any time, and if we detect no NPC collisions (too skilled/population too low) we can either spawn new NPCs with the required stats or require that character to move to a new location with more skilled NPCs (making it in town/the big city/the capital/the celestial palace/valhalla).

This is a very simple algorithm but, as you can see, it creates a fairly compelling environment with recurring character conflicts, inherent drama, contests of skill, and so on. Adding in more details such as relationships, families, memory, and so on can make it even more compelling, but even at the basic level it's already more compelling than just randomly generating NPCs.

Because we can put the skill gain locations into the world (training halls, for example), this also links our NPCs to the world. While you can increase your armorsmithing stat in the armory, that's not the only place you'll go. In addition to always needing to increase another stat somewhere else, the conflicts that arise with other characters have solutions that involve going to other places. IE, who can make the best silver breastplate for the prince's seventh birthday? Well, meet the prince -> gather silver -> talk to the jeweler -> bribe the jeweler with wine from the coast -> gather gems -> meet prince again -> forge breastplate -> party & final judging.

This kind of setup could involve playing as those characters, but the strength of this approach is that it's "open world". Switching characters is valuable.

You can have a bunch of different games based on this.

For example, you play a helpful newcomer trying to earn their place in a new city. Or you play a ghost. Or you play Dumbledore. Or you play the floating head that recruits Power Rangers. Or you're the manager of a gym. Or you're collecting Pokemon.

...

Right now, we generate 'points'. Our worlds are filled with plants and animals and buildings and people, but they stand alone.

By finding ways to create "paths" the player can follow, we can weave those paths into a world. Whether that's a physical world or a social world or some other world. It creates engagement, creates meaningful patterns and variations, and allows the fundamental variations in the content (such as size, stats, or personality) to matter more.

That's my thinking this week.

What do you think?

Wednesday, August 17, 2016

Exploration Changeups

One of the problems in exploration games is that the player always comes in from "on high".

That is, the player has full control over their movement and can see quite far. Not only can they choose whether to engage or not, they have extremely fine control over their engagement at all times, and can change their mind as they like.

Two problems with this.

1) It negates the impact of most content.
When you can see the content at range and keep an eye on it the whole time you close, it doesn't hold much mystique. This is especially true if you're relying on variants, because variations don't matter at range. They usually aren't even noticeable.

2) It negates the engagement of the content.
When the player has such precise control and good vision, it is difficult for the content to reach out and engage the player. This means that the content will just be a visual unless the player chooses to allow it to engage. Even if your content is brilliant and engages in many nuanced ways, that is painfully blunted if the player has this much control over its vector.

To fix these problems, we need to adjust both the player and the content. Not to a new normal, though: we're not looking to simply reduce the control and vision. We want to vary it wildly, because then the player will engage the content in a variety of ways at a variety of times, which will give the content a lot of life.

Here are some methods:

A) Vary the player's vision
We can reduce the player's vision. This can mean things like day/night. It can mean things like fog, rain, etc. But in addition to global changes, we can also use local arrangements - forests, caves, interiors, and other topologies that get in the way. Add additional complexity such as flashlights, flares, different vision modes, and even spotlights from space ships or something... all of these will vary the player's vision and make the same content affect them in different ways. Limited resources in certain vision modes are another way to add stress to this equation.

We can also increase the player's vision in a variety of ways, such as "hunter sense", or sonar, or a number of other ways of overlaying added data onto the normal audio/visual experience. Completely non-visual inputs such as audio should be considered as well: a heavy rain can make it impossible to hear a growling mountain lion hunting you.

Suddenly changing the player's sensory ranges is also fun. The player opens a door or window and suddenly they can see quite far... and something five feet away can see you just as well. This can be more terrifying than stumbling into that thing, because it seems that much closer due to your long vision. Letting the player trigger these events is very rewarding.

Secondary inputs such as sensors, remote monitors, and so on are a big factor in some kinds of games - for example, using a satellite to observe the surface of a planet. Another thing to remember is that you can increase vision while decreasing control using glass windows, raised platforms, wire fences, and so on. Anything you can see through/across, but not easily move through/across. Giving the player an option to scan ahead at the cost of time/resource can be valuable as well.

B) Vary the player's control
Reduce the player's control. This can be accomplished with things like vertical arrangements - climbing, sliding, and so on definitely reduce your control while also screwing with your vision. Things like thermals, flowing water, and currents can actively drag the player along, which can be fun if your game is designed for it. In addition, trampolines, intermittent vents, rope, bungee jumps, and zip-lines can give the player the option to move in an unusual fashion if they like, which works well as long as that unusual fashion offers advantages but also forces content engagement (IE, a bungee jump into a pit with a huge, hungry squid at the bottom, or a zip-line to the crumbling tower at the top of an ancient facility).

Those are just the start. We can also offer fundamental movement modes that have restrictions built in, such as parachuting, gliding, sinking, skiing, etc. In order for them to remain explorative, the constraints on these are usually going to be that you can't go backwards, or that it costs resources to go backwards. That way you can still explore, you just can't explore freely. Alternately, these alternate modes could be non-exploration parts of the game while still exposing you to explore-mode content in a new and very constrained way.

There are also some ways to do optional control, where the player is allowed to do things, but knows there will be repercussions. For example, they can fly their space ship into the ancient ruins, but it's going to damage them and make the wildlife hostile. Or they can unlock all the doors at a security station... but anything on the other side will be able to get out!

Lastly, you can flat-out take fine control away from the player. For example, if the player accepts a mission, you can cut to them being on the quest location. This requires your game to have that as part of the core experience, to avoid making it feel overly forced, but the idea of being able to simply put the player in any situation you want is fantastic from a content engagement perspective.

C) Create content that varies/reacts to the player's vision
The content itself can play with the player's vision. An easy example is a building: no matter how close you get to the outside of the building, there's an interior you can't see, or can only see through specific windows. Something which physically blocks the player's line of sight but also guarantees some content within that blocking thing. Things like pop-up walls are also useful, as long as the algorithm placing them specifically guarantees something worth finding as well.

The content can fuss with the vision in other ways. Animals might have stealth capabilities or be flat-out invisible (at least to some wavelengths). Alternately, plants might glow and actually improve your vision. Glowing frogs, mist-spitting plants, and so on. A plant may explode with a blinding flash of light or a huge cloud of smoke. Vision is also not just vision: animals that growl, plants that chime, a facility might whine so loudly it makes you deaf, etc.

The content can also move to protect itself from or expose itself to visuals - digging into the ground, coming out during the day, only flying in the fog, etc. This requires some AI, but it can be very interesting, especially if the player can take advantage of those changes by lying in wait or planting sensors.

The last option is to have content that reacts to what the player can see. For example, monsters that freeze when you look at them, or take damage as you look at them. Plants that grow if you watch them. Animals that panic and run if you can see them.

D) Create content that varies/reacts to the player's control
The most obvious way to have content vary player control is to have content be big, so that the player has to navigate it. Buildings are the easiest example - not only will the player have to walk around if they don't want to engage, but if they do engage, you'll be in a set of rooms with closed doors. So that varies both control and vision.

Also, content can do any of the things talked about a few bits ago - trampolines, ziplines, current generators, gravity cages, and other things can be part of content. Plants that blast air at you to drive you away, animals you can ride, and so on. It's best if these things have both upsides and downsides and can be either useful or hazards depending on the situation. That creates a lot of good emergent situations.

Indirectly, content can affect a player's control by adjusting global parameters. For example, you can't fly through dangerous fog (fog is content), you can only ski on snow, you can gather jetpack power on atmospheric planets but not on airless ones.

There's also the seriously meta options, such as having a plant that sings and will make you fall asleep if you don't keep wobbling the control stick.

E) Engage
After all that, you still need to have the content matter to the player. The way the content interacts with movement and vision is only one facet of how it can engage with the player.

Most exploration game content "engages" with the player by waiting for the player to come up and harvest it. There are a lot of better options, but you need to keep in mind the feel of your exploration game: being too forceful with your engagement is generally not great. This is why the idea of hostile content is annoying: I don't want to suddenly be in a battle with a giant monster or a military drone. Changing the gameplay mode without warning is just annoying.

The trick is to simply give plenty of warning. Animals don't just attack, and even hunting animals can be detected in advance by the player, who will see them in the bushes or hear them growling. Let the player choose whether to engage, push past, or route away. Of course, the player's exact situation will determine their choices. A player that ziplines into the middle of an angry hornet nest is in trouble... but they chose to zipline in!

Other than that, I would recommend you make most engagement systems adjustments, sinks, or fonts instead of forcing you to change game modes. Adjustments are things that affect your play - for example, a gravity ball that draws you in, or a wall of glowing lichen in a deep cave.

Sinks and fonts adjust the player's resources over time, usually getting more severe the closer you get. Draining or regenerating health and power are obvious. If you arrange you game to facilitate this sort of thing, you can do a lot more - for example, signal boosts or interference. Frying your pikmin. Covering you in ever-more goo so you move slower and slide down slopes...

F) Vary and Hook
Once you have players engaging with your content, you can extend that by creating nuances. For example, modular cat-predators: they always skulk around hunting prey, but as you swap out their various limbs, you get different specifics. This kind of variation only matters if the players are engaging: varying the content is worthless if the player chooses to not engage.

State changes are great as well, since you can layer content states. For example, the player might be able to restore power to a building. The nature of the building and its content might change when you do this - but there's also an opportunity for other content to change/pop into existence as well. Animals notice the lights. Sentry bots wake up. The elevator into the depths starts working. A radio signal broadcasts and someone hears it.

Layering and varying content adds much more life to the same amount of content.

You can also add in hooks by adding story elements, NPC commentary, and construction opportunities.

The easiest hook is safe zones: if there is some resource the player needs to regenerate (electricity, fatigue, etc), you can make specific content locations the only ways to get those. The specifics and the surroundings really start to matter!

Finale
Whether you're manually laying the content out or you're using an algorithm, a bit more care has to be taken in order to do these things properly. How you arrange them matters quite a lot: the meat of this experience involves how various content and constraints combine.

IE, a building alone is going to be dull. However, a building at the top of a rock spire surrounded by air-blasting plants that push you away... that's more interesting. Partly, the player has to figure out how to navigate the challenge. Kill the plants? Throw rocks to pre-trigger them? Using a jetpack? Land on the top of the spire with your amazing skill? Or all of those options one after the other!

In addition to the challenge, the player is being affected by the mystique. The limited navigation and vision means the building at the top remains interesting and engaging until the player reaches the top. At that point, the building's variations (windows, locked/unlocked doors, content contained, outlying modules) immediately matter to the player and they have to soak that up all at once at short range.

Anyway, that's what I've been thinking about recently. If you have any opinions, let me know.

Monday, August 15, 2016

Exploration Play

For the past twenty or so years, I've been thinking about exploration games. I've created hundreds of prototypes and several tabletop games about exploration, so it still irks me to see video games that drop the ball.

Let's talk about specific techniques to make exploration gameplay fun.

For starters, flow is absolutely critical in this kind of game. Your goal is not to reward the player or keep them interested, but to keep them in their flow. Unfortunately, flow varies over time and all players are a bit different.

So 1) establish flow and 2) keep the flow flowing.

1) Establish Flow
Establishing flow is tricky, but to me a big part of it is letting the player smoothly adopt a variety of short- and medium-term goals, discarding and rearranging as they see fit. The problem is that most exploration games start off with "here's a three hour tutorial".

Well, here's three hours where there's no flow state.

Every time you interrupt the player unexpectedly, every time you tell them what to do, you're resetting their "flow counter". On the other hand, if they don't see enough implicit short- and medium-term goals, they can't start their "flow counter". So both are bad.

My focus when I create exploration prototypes is to create a lot of easy-to-grab short-term goals that lead into medium-term goals quite naturally. New players will grab at the obvious short-term goals and, in the process, learn medium-term goals.

For example, if you start up No Man's Sky, the first thing you'll notice is that there's a space ship. This is an extremely obvious short-term goal. The sparking engines also clearly show a medium-term goal: fix the engines. Debris, tall plants, glowing plants - these all give the player short-term goals and, in the process, they learn about resources and loot.

Unfortunately, No Man's Sky falls short in a number of ways aside from that. It takes a long time to figure out how to use resources, and it's easy to run out of power before you figure out how to restore your power. Inventory management is obnoxious and opaque. This isn't a tutorial failure: it's a fundamental design failure.

It'd be fun to talk about How I Would Have Designed No Man's Sky, but in the end the point is simple: don't have popups. Don't have a tutorial, don't have early-game achievements, don't have an integrated crafting menu or complicated fuel management.

Focus on having delightful short-term goals (glowing plants, chunky debris, space ship) and a variety of short-medium-term (mine-able obelisks, minute-long walks) and medium-term (ruins on a nearby continent, requiring 300 ore to upgrade) goals. Experienced players will automatically balance this stuff out with long-term goals, but newbies need this stuff to flow naturally and easily in layers.

2) Keep the flow flowing
"Flow state" isn't one permanent thing - players constantly shift gears, and all players shift at different times depending on their personal preferences and mood. Because of this, any game that focuses on keeping a flow state needs to allow the player to shift their play whenever they want to, and lower that barrier as much as possible.

The two pieces to this are opportunistic short-term goals and floating medium-term goals.

Opportunistic short-term goals are easy enough: while you're on a medium-term goal, there should be a variety of opportunities to do small things en route. For example, seeing and harvesting good resources while running along, or seeing a hazard in your way and having to route around it or endure it.

Be careful about getting too aggressive: the player should choose how deeply to engage with the short-term goal. Forcing them to fight or trapping them in a deep cave is just distracting. Those kinds of forced engagements can come at the end of a medium-term goal, though, as a finale.

The point is to let the players choose to do a few fast-cycle loops if they want to, because they may be wobbling towards the fast-cycle part of their flow.

Floating medium-term goals are the opposite. When the player finishes a medium-term goal, they'll choose the next medium-term goal based on a lot of criteria. One of those criteria is what they feel like doing next. So try to engineer it so they have a few very different medium-term goals. Basically, some that will push them to walk, some that will push them to fly, some that will push them to warp, some that will push them to build - whatever varied gameplay you have.

Coming up with a variety of classes of medium-term goal is critical to this. In general, I define a medium-term goal as something with several opportunities for short-term goals along the way. So you can set up your medium-term goals to allow the player to choose what kind of play mode they're going to enter and what kind of experiences they're going to have.

For example, many medium-term goals are about traveling for less than 10 minutes to a known destination. But others might be about hunting for a specific resource, one which can only be found in a particular play style. Other medium-term goals might involve setting things up properly to survive a new class of environment, or caring for a pet, or buying something from a distant shop, or anything else you can think of based on your available kinds of play.

As long as there's stuff to do along the way.

Allowing the player to fluidly "change bands" means the player can stay in their flow state for longer, since as their mood changes, they can change their play.

3) Long-Term Structure
Exploration games have a few fatal flaws, but one of the big ones is that they're typically crafting/base-building games. By default, neither of those styles of gameplay actually makes sense for exploration. Exploration features a random mishmash of results, while crafting requires specific inputs and base-building typically locks you down to a location.

Base-building is largely a solved problem: either allow the player to take their base along, or allow players to revisit their built bases quickly and easily.

But crafting is still an issue. NMS shows this flaw in spades.

Because launching into space requires about six different resources (worst case), that means every planet must have those six resources within walking distance at all times. This leads to planets all feeling the same, even if they have wildly different visuals.

There are some simple techniques you can use. First off, make basic movement rely on no more than one resource (perhaps zero resources). If the only thing required to get into space was hydrogen, great. Every planet can have hydrogen on it, perhaps in different forms. The rest of the resources can be radically more scattershot.

A fantasy exploration game might require you to eat once in a while, but you can eat almost anything. Every biome just needs to have something vaguely edible in it.

Another simple technique is to use categorized resources instead of specific resources. IE, rather than requiring iron specifically, you could use any structural resource. Rather than requiring plutonium, any energy resource will work. They can have different stats, but any of them can get your crafting off the ground. This means that rare resources can fill the same slot as common resources, just be substantially better in some way.

Moreover, this allows for transmutation recipes. For example, if you just need to have any structural resource, you can turn oil (a fuel resource) into plastic (a structural resource) using some kind of machine.

The idea here is that the player is almost never "stuck" on a particular resource. They may get themselves stuck by insisting on using a specific rare resource if they like, but the game never says "you can't build X because you didn't find any copper". You can substitute in a variety of materials instead, including converting unsuitable materials via some time-consuming process.

This means the player is free to explore. When they find Xenocite, sure, it's just another structural element, but the resulting stats are off the charts. Build an engine turbine out of this, it'll be able to withstand immense strain and therefore you can go ten times faster than the same turbine built out of iron. Same thing, radically different parameters.

This also means you can let the player be isolated. You don't need a universal market everywhere, you don't need every resource everywhere. Let the player feel like they're out in the boonies or someplace super rare and weird.

Construction is also easy to tie into this, if your game has more than simply crafting. Bases made out of many different materials will all feel radically different and have different parameters. Just remember to solve the "base is left behind" problem.

4) Create Meaning
Exploration needs to have meaning to the player in order to make it fun.

A) Make it gorgeous. If the player wants to take pictures, they'll want to explore. Don't forget the audio.

B) Connect it to existing meaning. NMS has dinosaurs and trees, both of which are familiar and carry meaning already. Their alien species also feel familiar, callbacks to things you've seen before. Similarly, many of the stories are vignettes that simply tug on existing meaning - IE, a terrified warrior asking if you'll help him run away.

C) Chains of content. You can create meaning by making pieces change over time. For example, helping person A will make person B attack you later, or whatever. This is easy to script, but randomly generated chains need to be done carefully because the player will quickly start to categorize them and their deeper meanings will vanish.

D) Personalization. Allow the player to customize things (recruit friends, build bases, etc), then subject them to a variety of threats that test fitness and pull the player into defending the weak elements. The player will automatically feel strongly about something they own, so threaten the things they own. Just... not on a timer. Timers will break their flow.

E) Multiplayer. Allow the player to share things with other players and make it seem amazing. For example, screenshots and videos should inherently vary from player to player so that any player should think they have something unique to bring to the table, even if they're a newbie. Of course, sharing blueprints or seeding other player's content are also good opportunities to draw players in. This creates a bevy of medium-term goals as players strive to create/replicate something amazing.

Anyway, those are my thoughts.

Monday, July 25, 2016

Star Wars 7

Now that a few months have passed and I've rewatched the new Star Wars movie, it's time for a critique! I know this will have a widespread, profound effect on its sales and box office performance, so I had to think about it for a while.

My hatred of JJ Abrams is pretty well-known, and in the end that's going to be a huge shadow across this review. I have no respect for him as anything other than a very limited action director, even when backed up by seriously skilled heavy hitters. But let's talk about the movie.

First off, the movie is pretty decent. Better than the prequels by a long shot. Probably my third favorite Star Wars movie, and that's not bad at all.

It has very charming characters, most of whom are excellent actors. I love the newfound diversity, it makes the universe feel even bigger. I love the artful blend of CG and practical effects. Several of the sets are extremely nice, the props are all top-notch. The music and sound effects, of course, couldn't be much better. And the comedy bits are often in service of the characters, which is rare and very welcome.

Now, let's talk about the crappy parts!

I went with a group of 9 people to see it in theaters, ages 7 - 65. Several of them had seen it before. And we all came out of it confused and dissatisfied by the same elements. Some of us liked it, some of us hated it, but we all went "what the heck was up with that?" about the same things.

A big example was the tie fighter crash - you know, with Poe's coat. All of us were annoyed by that whole sequence.

But upon watching it again on DVD, I found the explanation was clearly written into the script, probably even shot correctly. It was just slapped up for a mere half-second and attention drawn away from it. Upon watching it knowing what to look for, it's clear that Poe takes off his coat, hangs it on his seat. It's clear Finn is ejected, so Poe obviously could have been, too. It's clear Finn finds the coat on the front canopy, not near the rear of the ship where Poe was seated, so it must have shaken free from the seat before it ejected.

The explosion still makes no sense, but let's just let that action schlock slide.

All of those elements are just fine on the written page. You can see the writers saying "THIS is how we'll give Finn that coat". Unfortunately, those elements weren't given to the audience on the screen. Even the parts that were on the screen, such as Poe taking off his coat, were not lingered on or highlighted. Instead, they were background elements in clips where the focus was clearly elsewhere, and even those clips were really tightly clipped.

This is how a magician does things - distract the audience with one hand while doing something with another. Unfortunately, if you do that in a movie, you end up with an audience that never knows you did the second thing and presumes you just have a basket full of continuity errors.

There are several elegantly written arcs in the movie, that one included. But half of the things on the screen are choppy and slapdash, badly paced and unpolished, like someone was in a hurry to slap more action on the screen.

For example, the double-defection of Finn and Rey, where they both have the exact same "I'm scared and gonna run away" arcs separately, within the same minute. This is a very badly paced element, and I can only presume that's not how it was originally written. Perhaps there was more time between them, or perhaps it was written so that Rey felt lost and betrayed by Finn and that was given time to grow on the screen to seed her own fear. Perhaps there were two scripts written, each with one of the characters panicking, and then for some reason both arcs were filmed and smashed together.

Another example: the murder of Han Solo. This is an amazing scene to most RPG players, because that's how a really good dark side arc in a game would go. It's completely legit, very powerful, especially the "thank you". It makes sense narratively and within the rules of the universe, as well as fitting in with every character.

Unfortunately, what we actually got on the screen wasn't so good.

"They're on your father's ship. You know, Han Solo, your dad?" "Yes, my father, Han Solo." "He's your dad." "Oh gosh, Evil McEvil noticed I still have good in me, gramps!" "Our son is up there, Leia!" "Our son, Kylo?" "Our son Kylo, Leia." "Grandpappy, help me, you're my grandpap." "He has good in him!" "Who, our son, Kylo?" "Kylo, yes, our son." "My dad landed on the planet." "Your dad Han?" "Han, my dad." "Oh, that dad." "Gramps, give me strength!" "Hello, Kylo my son. You still have good in you!"

I have a feeling that the writers knew half their scenes wouldn't get to the screen, so they just wrote twice as many and crossed their fingers.

I get that feeling a lot, actually. Because this movie has two plots, and they are both pretty sad.

In one plot, a bigger, badder Death Star sits on its butt in the middle of nowhere waiting to be found. In the other plot, a bigger, badder Luke sits on his butt in the middle of nowhere waiting to be found. Both are full of plot holes and neither is even vaguely compelling or personal.

It's clear the "bigger Death Star" plot exists because Disney wanted to prove they were oldschool Star Wars fans who were going to make oldschool Star Wars movies. But it's also clear that they thought that plot was pretty threadbare, so they stole a plot from a different draft and shoved it alongside.

I think either of these plots could have been made hundreds of times better without much trouble by simply choosing one. If either had more screentime, the glaring holes could have been explained away. Instead, they're pushed past with action sequences in a desperate attempt to gloss over everything.

The third plot - big baddie that runs everything - is established as a next-movie thing, but it also looks extremely uninteresting. I've already covered all the ways they could have made that interesting in an earlier essay. For example, it could be a holocron. That'd be amazing: all the Sith are gone, it's just one dumb kid with delusions and a holocron, but the dark side still manages to be a threat.

Any way you cut it, the movie could have been a lot tighter with different priorities. The inclusion of clips like "whoo, damn that pilot is good!" and the exclusion of clips like explaining why they had the last 2/3 of the map on a galaxy view but still needed the first 1/3 means that the whole thing feels very schlocky, as if the only thing that really matters are the action setpieces and a few pieces of comedy for pacing.

I have to wonder. The editing seems pretty tight, so why are there so many clips and sequences that don't seem like they fit right? Why is there such a laser focus on stuff that would have been great either way, while letting stuff that could have been great lay as unpolished stumbling blocks? Is this because of the director? It sounds like it might be the fault of the editors.

The editors Mary Jo Markey and Maryann Brandon, JJ Abrams' primary editors for almost all his films.

I hate JJ Abrams.

Sunday, July 10, 2016

Games Writing: Thematic Elements and Motifs

So, I've been playing a lot of games that get a lot of press. Most recently, I played Metal Gear Solid Five.

This essay's gonna be full of spoilers for it.

If you've ever taken lessons on writing books or movies, you've probably learned about themes and motifs. These repeating elements bind your work together and make it ring. Done well, they lead the audience straight into your premise and bind them to it before they've even noticed.

In video games, these are even more important. Not only are they more effective, but they are also more easily applied than other writing elements since they can be worked into any part of the game, including both cut scenes and raw gameplay.

Let's talk concrete a bit. Let's do some MGSV spoiling!

One of the motifs of MGSV is the idea of being ripped apart but having to live on. Missing limbs, missing voices, missing pasts, missing futures. This motif is so prevalent it's literally the title of the game: "The Phantom Pain" refers to the main character's missing arm and, through it, all of the other linked elements in the motif.

The motif isn't used as well as it could be. It's really only brought up right at the beginning and then again in Skull Face's final scenes. It could have been a lot stronger by linking it into the many times pain or loss is brought up. The child soldiers lost their families and that pain pushed them into a life of murder and violence... why not frame it as a lingering pain? Why not link it to Big Boss's missing arm with a simple camera pan?

These seem like small things, but they really aren't. Having good motifs and themes will make your story resonate for a lot longer. Like a trumpet, you need to have a funnel of themes for the player to breathe through, and then the note will ring out loud and clear.

I kept playing MGSV in hope that they would pull it together, but they never did. Kojima was, as usual, focused almost entirely on flash and glamour instead of the underlying power of the story. In the end, the plot was a muddled mess.

How could themes have helped? How could motifs have brought it together? What was wrong with the writing in what most people consider a gem of a game?

Well, let's consider the revenge element. This is a theme that rings pretty clear, it's brought up a lot. I don't consider it very convincing, though: there was never really any time I felt "in tune" with the main cast's lust for vengeance.

That could have been helped by some pretty subtle changes to the game itself. For example, instead of the utterly useless chicken hat that they keep trying to force onto you when you fail a mission, they could have marked your murderer and made it very hard for him, in particular, to spot you. And it could stack - if you are killed by 10 different people in this level, 10 people are now a bit blind.

This would be more universally useful than the chicken hat, but it would also push the player towards taking vengeance. Not only are they angry at the jerk that murdered them, they know that person is now weaker and open to retribution... or at least open to being snuck past.

There are a lot of other vengeance-related gameplay things you could have done - for example, causing me to actually lose any of the NPCs I cared about would have worked. But that doesn't happen until the heart of the vengeance arc is complete.

There's no doubt that the vengeance arc is the strongest arc in the game. The intention with this theme is to show that everyone's actions descend from a deep rage, a lust for vengeance. It could have been addressed clearer, but the basic idea is extremely solid.

And it has an extremely powerful ending. Themes and motifs are intense, and can be used to build up a finale that leaves a hell of an impact. If you do it right, people will remember your story for decades. It'll stay in their head.

In MGSV, the vengeance arc comes to a head with the death of Skull Face. Injured and trapped by debris, Skull Face is at the mercy of the two main characters, both of whom have lost limbs to his schemes. Instead of killing him, they blow those limbs off of him, then tell him to kill himself if he wants, and walk away.

It's a hard-to-watch scene and a dark note, but then the stupid engineer nobody likes simply goes over and shoots him. Then goes "yay! I got vengeance!"

This would have been the perfect ending, if it had been paced a little better. Two people obsessed with their deep, decade-long fury set up their brutal plan for vengeance... and then some little shit with a small, recent grudge ruins it to take vengeance himself.

That could have been perfect, turning the whole concept of vengeance into a sour note, a farce. It would have been subtle, understated, and heavy. Like a trumpet, one of the best ways to use a theme in the end is to have it ring hollow.

But that's not what MGSV does. It doesn't pace it right, it doesn't hit it cleanly, and then it immediately sweeps away to a long set of interminable speeches that have almost nothing to do with vengeance. Even if they were about vengeance, they're filling a gap - a hollow, ringing space that needs to remain empty. The trumpet turns into a whimper when you fill the bell with glitter.

You can argue that the "real ending" of MGSV is better and not flubbed, but just as an example, this is how you would have turned the vengeance theme into a powerful ending.

The difficulty is that you really have to trust that empty space. The themes and motifs don't need your help, they need space. The player has to have time to digest it and let it grow. But once it does, it will stay with them forever.

Bioshock Infinite is another example of a badly flubbed ending, but in BI's case it was all done subconsciously. Say what I like about Kojima's lack of depth, he at least uses his themes consciously. Levine does not.

As I was playing BI and getting steadily more annoyed, I started to suspect the themes were used consciously, and the touch was just incredibly subtle. Of course, that wasn't the case, and BI's plot ended up being trash.

What themes?

It's clear that BI was written by dads, and the trashy plot progression seemed to be leading to one hell of a powerful ending: DeWitt had to learn to let his daughter go, let her be her own person, maybe even kill himself to save her from his own endless meddling.

All of the game's muddy and backtracky plot elements - all the racism, all the sexism, all the old friends you have to kill, the other me, the past me, the future me, the alternate daughters that have all suffered at my hands - all of that would suddenly shine and shout if it turns out that the problem is just me. It's all... me fucking it up. Me judging it by my own biases. Me acting to protect and control, only to end up poisoning everything because my grip is too damn tight.

I know some people liked the faux-philosophical ending of BI, and I won't say you're a bad person for it, but it doesn't hook into the themes and motifs set up during the play. And the reason is because Levine didn't realize he was including themes of being an oppressive daddy figure. He just... is one. It bled in naturally, mixed with the natural juices of murderous first-person gameplay, and turned into a truly noxious mix.

It doesn't cost anything to get an ending right. It's actually cheaper, because you don't need another fifteen minutes of pomp and glitter. Just a slow pan across a scene you already built.

But it takes an enormous amount of trust in yourself, in your writing, in your editing. It takes a lot of convincing to tell yourself "the game should just... end here. I don't need to make a long speech. I don't need to set up the next game. I don't need to do anything. I can just... hold here for ten seconds and roll credits."

There are plenty of movies and books that do just that. For example, Fight Club. Fight club's ending is probably still in your head. You probably remember it even now, the self-inflicted gunshot, the burning city.

But in games it's super rare. Games are too nervous to let things sit, to let things ring on their own. Devs want to fill that space, and in the end it just muddies things up and leaves the endings tasting of sawdust.

What's the last game ENDING you remember?

I bet you remember a lot of middles! But the endings?

...

Anyway, this essay was just written immediately before bed, no editing. I hope you enjoyed it anyway, let me know what you think.

Wednesday, July 06, 2016

!ScriptableObject

Recently, a lot of people have been referencing Richard Fine's video on ScriptableObjects. I'm gonna go ahead and rebut it.

A few details: I loved ScriptableObjects. I made videos about how to use them. I certainly don't dislike Richard Fine, I think he does pretty solid work. But I think his obsession with ScriptableObjects is really muddying waters, and his video is misleading.

Things have changed in the prefab world.

Used to be that if you wanted something shared everywhere, you used ScriptableObjects. No matter the scene, no matter the situation, references to that ScriptableObject would point to the asset in the project, and one change would change it everywhere.

However, in the past few years, prefabs have grown a lot of muscle. It's easy to overlook, because prefabs wear baggy clothes, but now you can (and should) use prefabs for many of the things he recommends using ScriptableObjects for.

(And for the rest, you should use a real database.)

You can reference uninstantiated MonoBehaviours now. You can read their values, call their functions, trigger their events - all without instantiating. What does this mean?

It means that everything ScriptableObjects used to be good for, MonoBehaviours can do... and can unlock much more powerful patterns than ScriptableObjects tend to allow. Unity was built around the concept of prefabs and MonoBehaviours, and now we can merge that power with prefab referencing.

Let me describe the patterns I'm using in The Galactic Line. These are MonoBehaviours-with-muscly-prefabs patterns.

The Magic Mixin
I have a lot of space ship parts. I don't like instantiating them, because they're heavy: they have LODed visuals, sound clips, lights, lots of stuff that I want to leave on the cutting room floor if the ship is too far away to see... but I still want to simulate the ships. Hundreds of ships you can't see, still being simulated as their resources drain away and their mission timers tick up.

Ships are easy enough to simulate, but you need each of their parts to tell you what it does as time passes. What does this reactor do? It drains water and creates power. It drains antimatter and creates power, heat, and radiation. It's pressurized. It's not pressurized. It has these external visuals and collision meshes, these internal visuals and collision meshes. It makes these sounds in these situations. It has beds in it for some reason. Or maybe not.

When I get close, these parts resolve into a GameObject. They have to, because we have to see them and hear them in the scene. I could bend over backwards to avoid making a prefab... but why? It makes sense to make it a prefab, that's what prefabs are for.

The problem is that I want to access all that juicy functional stuff without instantiating the part.

I could make all of them ScriptableObjects, but then we have a staggering number of floating loose ends. A radiation-production ScriptableObject saved off in some other directory, values specific to this reactor. It makes more sense to have a radiation-production MonoBehaviour and stick it onto the part. I can just customize it right there, no need to have dangling assets. That's what the GameObject is for.

And I can access all of that directly, without instantiating anything. If I want to know how much power this reactor creates and how fast it guzzles fuel, I just ask it. If I want to know if it's air-tight, I just ask it if it has an air-tight mixin. If I want to know what its UI thumbnail is, I just ask it. Want to know what sounds it makes? Just ask. I need to simulate ten weeks of warp travel? Just ask it for those values and multiply by ten weeks.

I can load everything I need onto the part prefab. It doesn't matter how complex the part is. It doesn't matter whether it involves nested objects or flat mixins. Modders can clone and alter the part, and it won't screw up the default because the values are per-prefab.

In addition to being super easy to take care of and keep track of, I can then just drop it into the scene. Whether it's in play mode or edit mode, I can drop it into the scene and it will instantly be the thing it is. I can mount in anything I want, visually. LOD? Or not. Lighting or not. Hell, additional cameras displaying to holographic monitors? Sure. Sounds that play differently depending on how much the generator is being taxed? Why not!

In this way, anyone can create ship components, drop on the relevant mixins (such as "Reactor" and "PressurizedSpace"), save it. They know what they'll get, and the game engine automatically optimizes to prevent any bloat. Advanced users can hook UnityEvents up to create nice triggers and visuals, or even create new scripts. Just drop 'em in. No loose ends, no complicated dependencies.

Now, if the thought of a largely undifferentiated ball of objects makes you cringe... this method of creating and saving content is a fundamental in Unity. This is how Unity is engineered to work, and this is how it works most easily.

You can engineer around it, but why? Use the engine in the way it's meant to be used, and you'll have a much easier time of it.

The Meta-Instantiator
My ships have a lot to keep track of, but I don't instantiate any of the parts if I can get away with this. This means I can have a fleet of Star Destroyers, each containing thousands of crew members, and from the perspective of the game it's just a bit of data that gets processed whenever it needs to be.

The ship has a link to the blueprint prefab for the ship class, which in turn contains all the ship parts. If I instantiate that blueprint, I get a nice, shiny ship full of visuals and noises and stuff.

But I don't have to instantiate it. Instead, I crawl through the parts compiling a list of all the resources and potential mission parameters and that jazz. A small algorithm calculates out the next "keyframe" in the ship's future - when the mission completes, when resources get dangerously low, when it reaches its destination, etc.

The universe sim trickles forward at whatever pace the player wants, and when the in-universe time hits that keyframe, we crawl through the ship again to find the new situation and calculate out the next keyframe. This simple method allows us to have thousands of Star Destroyers without any slowdown at all. No per-frame update, we don't even really need an in-scene object to represent them. (And, since they're probably 500 light years away, that's good.)

Well, we get close to a fleet of Star Destroyers, and therefore the ones nearby start getting instantiated into the game world. The player accidentally rams one, breaking one of those big engines. An NPC commander is generated and yells at the player.

Oh no, this is awful! How do we remember things like a specific engine being broken, or a specific commander existing? We're just referencing a blueprint!

... just save the instance as a custom ship.

Since the blueprint contains a reference to its prefab and each component contains a reference to its own prefab, we can do whatever we want. We can easily save this "baked" blueprint, and then compare its stats to the changes in the definitions of things like engines and reactors. We could even just save the one damaged component, and leave the rest as references.

We can also generate a mission to repair the ship, and when the mission completes, we can delete the custom blueprint and restore it to an ordinary blueprint reference. We could also save the commander - either as part of this ship or separately, as we prefer.

Unlike a ScriptableObject, a prefab can easily be cloned, compared, reloaded, partially cloned, merged, instantiated piecemeal...

The Monster's Database
If you're a fan of ScriptableObjects, hopefully by now you're thinking "well for your specific application, sure, but IN GENERAL-"

Most of the uses of ScriptableObjects are as data objects. The big advantage is that there's no extra stuff.

For example, I have a list of various factions and species. If each was a MonoBehaviour, I could drag it onto a property on another class in the same way as I could do with a ScriptableObject - it'd automatically resolve the reference to the prefab as a reference to the specific MonoBehaviour on the prefab. It'd behave exactly like a ScriptableObject, but it'd have a GameObject lurking in the background being... nonoptimal.

I mean, why would you ever instantiate a whole faction, right? Just drag it into the scene? You'd never need that, so it's just junk stapled onto my data class!

I could argue that it allows for mixins, but we already did that. Let's argue for something else.

Before that level of garbage starts to get noticeable, we run into another problem: managing hundreds of ScriptableObjects is just as obnoxious as managing hundreds of prefabs.

There's a reason why GameMaker and RPGMaker use databases for this kind of thing: databases are a really great way to handle it. You could manipulate the editor to create a pseudo-database front end for your ScriptableObjects (or your prefabs), but... JUST MAKE A DATABASE. It's faster, less overhead, and can be easily exported and imported from Excel or an HTML form or whatever.

The big problem with databases is that it's hard to drag a specific entry into a field in the inspector. I don't know the best solution for this, right now I'm using an editor trick to fake it, but it's not very good.

In the end, my thoughts are simple: if you have dozens of entries, you probably need a database. If you have only a few, the extra garbage of having a GameObject attached isn't enough to worry me, and you can usually leverage mixins to add a lot of extra functionality on the cheap.

The Custom Prefab
My argument is simple: the prefab is now more powerful than the ScriptableObject.

In the video above, Richard Fine creates a ScriptableObject to handle playing custom explosion sounds. This is the part of the video that upsets me the most, because it's a magic handwave that hides the fact that it does nothing useful at all.

There's no reason to have a ScriptableObject "ShellExplode" floating around separately from the shell prefab that's going to explode. Just put it on the goddamn shell. Even the "play mode editing" would work the same way, because you're editing the prefab and it gets instantiated every time you hit shoot!

And, of course, now you just have A Shell Object instead of a shell object and some random dangling object in another directory that may or may not be referenced correctly. Moreover, you can easily clone the shell prefab and create your Big Boss Shell and your Tracer Shell and your Rocket Shell, tweak away!

It's not magic, it's the way Unity is built to work best.

The idea that a prefab is somehow "fragile" is not true any more. The classic example of a ScriptableObject is that if you have ten monsters, they can all have the same stats and you'll never "accidentally" edit just one monster to have different values.

If you have a lot of monsters, you'll probably be using a monster spawner that references a prefab, rather than hardcoding every monster. Even if you do hand-place each monster, changes to the prefab automatically update instances, as long as the instance's values haven't been manually altered. This works per property.

So, for example, if I have ten orcs and I want one of them to have extra HP, I can increase the HP. And I change his AI role to "leader". And I add a potion to his inventory. And I put a hat on him. Later, I change the orc prefab's damage from 4 to 6. The orc I modified will have his damage correctly updated, while still keeping his hat and potion and HP and AI role!

Sure, it's possible to accidentally change a value and not realize it, but that seems inconsequential compared to the overhead of needing a new, permanent asset file in your project directories for every slightly tweaked monster.

That's the point of Unity. The point of Unity's entire approach is that you can tweak things in scene view! Using ScriptableObjects to "work around" that is like "working around" the game of basketball by taking out the ball. Yeah, you could probably come up with something, but it's not going to be a very effective use of your basketball pros or your basketball courts!

Use Interfaces and Delegates
I've seen a few other arguments for ScriptableObjects - for example, externalizing coroutines so you can plug them in willy-nilly, or using delegates bound up in ScriptableObjects to do things like flexible AI processing.

Just... uh... just use C#.

Not to sound elitist, but C# has delegates and interfaces already. Use them. Don't find an excuse to wrap them in ScriptableObjects, just mainline the stuff.

Unity's support for these in the inspector view is kinda crappy, which is the big argument against it. Fortunately, you can use UnityEvents instead of delegates, and those do show up in the inspector fine.

Interfaces are similarly inspector-unfriendly, but they're very powerful and useful and don't limit you to either a ScriptableObject or a MonoBehaviour - you can use either, or even a raw C# class, or have instances of all three for different applications that are referenced from a single system!

Personally, I think using MonoBehaviour mixins as implementations of interfaces is really underestimated, but that's another topic entirely.

Use ScriptableObjects
Am I arguing that ScriptableObjects are useless?

No, not at all. They are more optimal than prefabs, so if it occurs to you to use them, you should use them. They're especially nice when it comes to instantiating them outside of the scene, or moving references between clients.

Fundamentally, ScriptableObjects are classes. That is, you've written lines of code. I generally suggest using them when you can write less code by using them, and I tend to find that means situations where I need to create and track arbitrary references and complex data.

I've stored options menu defaults in ScriptableObjects, level code, galaxy definitions...

But, in the end, I've never found them to be much earthshakingly better than either using prefabs or raw data. So I only use them when I'm in the mood to optimize.

ScriptableObjects CAN do a lot of things, but that's because they're a C# class. They're not substantially better at those things than either a MonoBehavior or a C# class. Any optimization you can get by using them is marginal, and they don't offer any particularly astounding new patterns or workflow.

I'm not against using them. I just don't want people to think they can do these amazing things... without ever realizing that simple prefabs can already do those things, and many other things at the same time.