Files
stoneheart_at_home/app/d3d_scene_win32.cpp
T

675 lines
33 KiB
C++

#define NOMINMAX
#include "d3d_scene_win32.hpp"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <iterator>
#include <limits>
#include <utility>
namespace settlement::viewer {
namespace {
using Microsoft::WRL::ComPtr;
struct Point { float x, y, z; };
struct Color { float r, g, b; };
struct Vertex { Point position; Color color; };
constexpr Color rgb(int r, int g, int b) {
return {static_cast<float>(r) / 255.f, static_cast<float>(g) / 255.f, static_cast<float>(b) / 255.f};
}
constexpr Color shade(Color color, float amount) {
return {color.r * amount, color.g * amount, color.b * amount};
}
class Mesh {
public:
std::vector<Vertex> vertices;
void quad(Point a, Point b, Point c, Point d, Color color) {
vertices.insert(vertices.end(), {{a, color}, {b, color}, {c, color}, {a, color}, {c, color}, {d, color}});
}
void flat(float a, float b, float c, float d, float z, Color color) {
quad({a, b, z}, {c, b, z}, {c, d, z}, {a, d, z}, color);
}
void box(float x, float y, float z, float w, float d, float h, Color color) {
const float a = x - w / 2, b = y - d / 2, c = x + w / 2, e = y + d / 2, top = z + h;
flat(a, b, c, e, top, color);
quad({c, b, z}, {c, e, z}, {c, e, top}, {c, b, top}, shade(color, .76f));
quad({a, e, z}, {c, e, z}, {c, e, top}, {a, e, top}, shade(color, .62f));
}
void track(GridPosition from, GridPosition to, Color color) {
const float x = static_cast<float>(from.x), y = static_cast<float>(from.y);
const float end_x = static_cast<float>(to.x), end_y = static_cast<float>(to.y);
constexpr float half = .035f;
flat(std::min(x, end_x) - half, std::min(y, end_y) - half,
std::max(x, end_x) + half, std::max(y, end_y) + half, .016f, color);
}
};
void terrain(Mesh& mesh, const World& world, const SceneView& view) {
mesh.box(static_cast<float>(world.width() - 1) / 2.f, static_cast<float>(world.height() - 1) / 2.f, -.65f,
static_cast<float>(world.width()), static_cast<float>(world.height()), .64f, rgb(133, 107, 71));
for (int y = 0; y < world.height(); ++y) {
for (int x = 0; x < world.width(); ++x) {
const GridPosition cell{x, y};
const float px = static_cast<float>(x), py = static_cast<float>(y);
const int variation = (x * 17 + y * 29 + x * y * 5) % 12;
const bool walkable = world.is_walkable(cell);
auto surface = walkable ? rgb(123 + variation, 157 + variation, 104 + variation) : rgb(103, 118, 106);
if (view.move_source == cell) surface = rgb(219, 189, 113);
if (view.cursor == cell) surface = view.valid_cursor ? rgb(150, 205, 219) : rgb(223, 139, 124);
mesh.flat(px - .50f, py - .50f, px + .50f, py + .50f, 0, shade(surface, .90f));
mesh.flat(px - .48f, py - .48f, px + .48f, py + .48f, .004f, surface);
if (walkable) continue;
const float height = .50f + static_cast<float>(variation % 4) * .10f;
mesh.box(px, py, .004f, .75f, .76f, height * .45f, rgb(114, 131, 119));
mesh.box(px - .06f, py - .04f, height * .45f, .55f, .59f, height * .55f, rgb(146, 157, 143));
}
}
}
void resources(Mesh& mesh, const World& world) {
for (const auto& node : world.resource_nodes()) {
const float x = static_cast<float>(node.position.x), y = static_cast<float>(node.position.y);
if (node.site != ResourceSite::Natural) {
mesh.flat(x - .43f, y - .43f, x + .43f, y + .43f, .025f, rgb(133, 103, 70));
}
if (node.site == ResourceSite::Mine) {
mesh.box(x, y, .025f, .74f, .76f, .09f, rgb(62, 67, 63));
mesh.box(x - .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67));
mesh.box(x + .28f, y, .05f, .12f, .65f, .46f, rgb(140, 102, 67));
mesh.box(x, y, .51f, .76f, .65f, .11f, rgb(181, 141, 90));
} else if (node.quantity == 0) {
if (node.growth_at != 0 || node.reserved_workers != 0) {
mesh.box(x, y, .025f, .16f, .14f, .15f, rgb(100, 150, 85));
}
} else if (node.type == ItemType::Wood) {
mesh.box(x, y, .02f, .19f, .19f, .75f, rgb(117, 83, 57));
mesh.box(x, y, .58f, .72f, .73f, .36f, rgb(67, 112, 72));
mesh.box(x - .07f, y - .07f, .94f, .49f, .49f, .29f, rgb(91, 143, 85));
} else if (node.type == ItemType::Berries || node.type == ItemType::Flax) {
const bool flax = node.type == ItemType::Flax;
if (node.type == ItemType::Berries && node.foraging_enabled) {
mesh.flat(x - .39f, y - .39f, x + .39f, y + .39f, .028f, rgb(159, 187, 102));
}
for (int i = 0; i < 3; ++i) {
const float shift = static_cast<float>(i - 1) * .19f;
mesh.box(x + shift, y - shift * .56f, .03f, flax ? .12f : .30f, flax ? .13f : .33f,
flax ? .34f : .24f, flax ? rgb(98, 143, 80) : rgb(78, 133, 75));
mesh.box(x + shift, y - shift * .56f, flax ? .37f : .27f, .13f, .15f, .08f,
flax ? rgb(147, 175, 229) : rgb(207, 105, 135));
}
} else {
mesh.box(x, y, .03f, .51f, .53f, .32f, rgb(151, 159, 150));
}
}
}
void room_part(Mesh& mesh, GridPosition cell, RecipeId recipe, Color color, bool draft) {
const float x = static_cast<float>(cell.x), y = static_cast<float>(cell.y);
if (recipe == RecipeId::BuildFloor) {
mesh.flat(x - .495f, y - .495f, x + .495f, y + .495f, .013f, shade(color, .76f));
for (int i = 0; i < 4; ++i) {
const auto strip = static_cast<float>(i) * .24f;
mesh.flat(x - .49f, y - .48f + strip, x + .49f, y - .25f + strip, .015f,
shade(color, i % 2 ? 1.f : .93f));
}
} else if (recipe == RecipeId::BuildWall) {
if (draft) {
mesh.box(x, y, .03f, .92f, .92f, .09f, shade(color, .69f));
mesh.box(x, y, .12f, .91f, .91f, .16f, color);
} else {
mesh.box(x, y, .02f, 1.f, 1.f, .73f, color);
mesh.box(x, y, .75f, 1.f, 1.f, .10f, shade(color, 1.13f));
}
} else {
const bool along_x = recipe == RecipeId::BuildDoorAlongX;
for (const float side : {-1.f, 1.f}) {
mesh.box(x + (along_x ? side * .40f : 0.f), y + (along_x ? 0.f : side * .40f),
.02f, along_x ? .20f : .62f, along_x ? .62f : .20f, .73f, color);
}
mesh.box(x, y, .75f, along_x ? 1.f : .62f, along_x ? .62f : 1.f, .10f, shade(color, 1.13f));
if (!draft) {
const auto leaf = [x, y, along_x](float side, float inward, float height) {
return along_x ? Point{x + side, y + inward, height} : Point{x + inward, y + side, height};
};
mesh.quad(leaf(-.28f, 0.f, .04f), leaf(-.06f, .40f, .04f), leaf(-.06f, .40f, .66f),
leaf(-.28f, 0.f, .66f), shade(color, .75f));
const auto handle = leaf(-.09f, .32f, .37f);
mesh.box(handle.x, handle.y, handle.z, .06f, .06f, .06f, rgb(215, 183, 107));
}
}
}
void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview);
void draw_furnishing(Mesh& mesh, GridPosition cell, RecipeId recipe, Color wood, Color detail) {
const float x = static_cast<float>(cell.x), y = static_cast<float>(cell.y);
if (recipe == RecipeId::BuildMedicineCabinet) {
mesh.box(x, y + .10f, .03f, .64f, .35f, .61f, wood);
for (const float offset : {-.22f, 0.f, .22f}) {
mesh.box(x + offset, y - .13f, .34f, .15f, .15f, .22f, detail);
mesh.box(x + offset, y - .13f, .56f, .10f, .10f, .056f, shade(detail, .73f));
}
} else if (recipe == RecipeId::BuildMiningRack) {
mesh.box(x, y, .03f, .74f, .45f, .12f, wood);
for (const float offset : {-.25f, .25f}) {
mesh.box(x + offset, y + .1f, .15f, .09f, .10f, .62f, wood);
}
mesh.box(x, y + .1f, .64f, .64f, .10f, .11f, wood);
for (const float offset : {-.15f, .15f}) {
mesh.box(x + offset, y - .04f, .22f, .045f, .05f, .39f, shade(wood, 1.25f));
mesh.box(x + offset, y - .04f, .59f, .23f, .08f, .07f, detail);
}
} else {
mesh.box(x, y, .025f, .71f, .58f, .34f, shade(wood, .82f));
mesh.box(x, y, .37f, .77f, .62f, .10f, wood);
mesh.box(x, y - .12f, .46f, .62f, .12f, .37f, wood);
mesh.box(x, y - .15f, .79f, .48f, .15f, .10f, detail);
}
}
void draw_room_plan(Mesh& mesh, const RoomPlan& plan, bool preview, bool valid) {
const auto ink = !valid ? rgb(203, 113, 101) :
(preview ? rgb(169, 224, 232) : rgb(104, 176, 212));
for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) {
const GridPosition cell{x, y};
room_part(mesh, cell, plan.recipe_at(cell), ink, true);
}
}
if (const auto furnishings = plan.furnishings()) {
for (const auto& part : *furnishings) {
if (part.recipe == RecipeId::BuildBed) {
draw_blueprint(mesh, {part.position, part.recipe, part.bed_base}, preview);
} else {
draw_furnishing(mesh, part.position, part.recipe, ink, shade(ink, .73f));
}
}
}
}
void draw_gabled_roof(Mesh& mesh, float left, float top, float right, float bottom, float eaves,
float ridge, bool along_x, Color tiles, Color gable) {
if (!along_x) {
std::swap(left, top);
std::swap(right, bottom);
}
const auto point = [along_x](float x, float y, float z) {
return along_x ? Point{x, y, z} : Point{y, x, z};
};
const float middle = (top + bottom) / 2.f;
constexpr float overhang = .12f;
for (const float edge : {left, right}) {
const auto peak = point(edge, middle, ridge);
mesh.quad(point(edge, top, eaves), point(edge, bottom, eaves), peak, peak, gable);
}
left -= overhang;
right += overhang;
const auto slope = [&](float edge, float light) {
constexpr std::array shades{.90f, 1.03f, .95f, 1.08f};
for (std::size_t i = 0; i < shades.size(); ++i) {
const float a = static_cast<float>(i) / static_cast<float>(shades.size());
const float b = static_cast<float>(i + 1) / static_cast<float>(shades.size());
const float y1 = std::lerp(edge, middle, a), y2 = std::lerp(edge, middle, b);
const float z1 = std::lerp(eaves, ridge, a), z2 = std::lerp(eaves, ridge, b);
mesh.quad(point(left, y1, z1), point(right, y1, z1), point(right, y2, z2),
point(left, y2, z2), shade(tiles, light * shades[i]));
}
};
slope(top - overhang, .93f);
slope(bottom + overhang, 1.12f);
mesh.quad(point(left, middle - .035f, ridge + .02f), point(right, middle - .035f, ridge + .02f),
point(right, middle + .035f, ridge + .02f), point(left, middle + .035f, ridge + .02f),
shade(tiles, .72f));
}
void draw_room_roofs(Mesh& mesh, const World& world) {
struct Tile {
RecipeId structure = RecipeId::SawPlank;
RoomTemplate furnishing = RoomTemplate::Empty;
bool visited = false;
};
const auto width = static_cast<std::size_t>(world.width());
std::vector<Tile> map(width * static_cast<std::size_t>(world.height()));
const auto tile = [&](GridPosition cell) -> Tile& {
return map[static_cast<std::size_t>(cell.y) * width + static_cast<std::size_t>(cell.x)];
};
for (const auto& order : world.production_orders()) {
auto& cell = tile(order.position);
if (is_room_part(order.recipe) && order.state == JobState::Completed) {
cell.structure = room_part_shape(order.recipe);
}
switch (furnishing_shape(order.recipe)) {
case RecipeId::BuildMedicineCabinet: cell.furnishing = RoomTemplate::Doctor; break;
case RecipeId::BuildMiningRack: cell.furnishing = RoomTemplate::Miner; break;
case RecipeId::BuildLoom:
case RecipeId::WeaveCloth: cell.furnishing = RoomTemplate::Weaver; break;
default: break;
}
}
const auto in_bounds = [&](GridPosition cell) {
return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height();
};
const GridPosition neighbors[] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
const auto intact = [&](const RoomPlan& plan) {
for (int y = plan.first.y; y <= plan.last.y; ++y) {
for (int x = plan.first.x; x <= plan.last.x; ++x) {
const GridPosition cell{x, y};
if (tile(cell).structure != plan.recipe_at(cell)) return false;
}
}
return true;
};
constexpr Color finishes[] = {rgb(146, 94, 66), rgb(107, 136, 76), rgb(86, 116, 136), rgb(169, 91, 65)};
std::vector<GridPosition> floor;
const auto visit = [&](GridPosition cell) {
if (!in_bounds(cell)) return;
auto& entry = tile(cell);
if (entry.visited || entry.structure != RecipeId::BuildFloor) return;
entry.visited = true;
floor.push_back(cell);
};
for (int y = 0; y < world.height(); ++y) {
for (int x = 0; x < world.width(); ++x) {
floor.clear();
visit({x, y});
if (floor.empty()) continue;
GridPosition first{x, y}, last{x, y};
auto finish = RoomTemplate::Empty;
for (std::size_t i = 0; i < floor.size(); ++i) {
const auto from = floor[i];
first.x = std::min(first.x, from.x);
first.y = std::min(first.y, from.y);
last.x = std::max(last.x, from.x);
last.y = std::max(last.y, from.y);
if (tile(from).furnishing != RoomTemplate::Empty) finish = tile(from).furnishing;
for (const auto offset : neighbors) visit({from.x + offset.x, from.y + offset.y});
}
RoomPlan plan{{first.x - 1, first.y - 1}, {last.x + 1, last.y + 1}};
if (!plan.valid_size() || !in_bounds(plan.first) || !in_bounds(plan.last)) continue;
// A room from an older save has the same completed floor and perimeter as a new room.
for (const auto side : {RoomSide::North, RoomSide::East, RoomSide::South, RoomSide::West}) {
plan.entrance = side;
if (!intact(plan)) continue;
const bool along_x = side == RoomSide::East || side == RoomSide::West;
const int span = along_x ? plan.last.y - plan.first.y : plan.last.x - plan.first.x;
draw_gabled_roof(mesh, static_cast<float>(plan.first.x) - .5f, static_cast<float>(plan.first.y) - .5f,
static_cast<float>(plan.last.x) + .5f, static_cast<float>(plan.last.y) + .5f, .85f,
.85f + std::min(.24f * static_cast<float>(span + 1), 1.65f), along_x,
finishes[static_cast<std::size_t>(finish)], rgb(176, 127, 82));
break;
}
}
}
}
void construction(Mesh& mesh, const World& world, BuildingView building_view) {
const auto workshop = world.carpenter_workshop();
if (workshop) {
const auto x = static_cast<float>(workshop->x);
const auto y = static_cast<float>(workshop->y);
mesh.box(x, y, .02f, .87f, .74f, .36f, rgb(142, 95, 59));
mesh.box(x, y, .38f, .92f, .77f, .12f, rgb(209, 161, 104));
mesh.box(x, y - .12f, .50f, .59f, .12f, .08f, rgb(180, 190, 191));
mesh.box(x - .29f, y - .12f, .52f, .16f, .17f, .12f, rgb(123, 68, 46));
}
for (const auto& storage : world.storages()) {
const float x = static_cast<float>(storage.position.x), y = static_cast<float>(storage.position.y);
mesh.box(x, y, .02f, .66f, .62f, .44f, rgb(160, 110, 65));
mesh.box(x, y, .46f, .72f, .67f, .10f, storage.kind == StorageKind::Pantry ?
rgb(187, 120, 148) : rgb(202, 155, 91));
mesh.box(x + .34f, y, .30f, .052f, .13f, .13f, rgb(229, 195, 124));
}
for (const auto& order : world.production_orders()) {
if (is_carpentry_recipe(order.recipe) ||
(order.recipe == RecipeId::SawPlank && workshop == order.position)) continue;
const auto fixture = furnishing_shape(order.recipe);
const float x = static_cast<float>(order.position.x), y = static_cast<float>(order.position.y);
if (order.recipe == RecipeId::WeaveCloth) {
draw_furnishing(mesh, order.position, order.recipe, rgb(185, 140, 86), rgb(235, 225, 193));
continue;
}
if (!is_construction(order.recipe)) {
mesh.box(x, y, .025f, .71f, .58f, .34f, rgb(150, 110, 73));
mesh.box(x, y, .37f, .77f, .62f, .10f, rgb(199, 156, 100));
continue;
}
if (order.state != JobState::Completed) {
const auto marked = order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99);
mesh.flat(x - .44f, y - .44f, x + .44f, y + .44f, .03f, marked);
}
if (is_room_part(order.recipe)) {
const auto shape = room_part_shape(order.recipe);
if (building_view == BuildingView::FloorsOnly && shape != RecipeId::BuildFloor) continue;
if (order.state == JobState::Completed) {
room_part(mesh, order.position, shape, rgb(175, 123, 78), false);
} else if (shape != RecipeId::BuildFloor) {
room_part(mesh, order.position, shape,
order.state == JobState::Available ? rgb(121, 178, 195) : rgb(214, 171, 99), true);
}
} else if (fixture == RecipeId::BuildMedicineCabinet || fixture == RecipeId::BuildMiningRack ||
fixture == RecipeId::BuildLoom) {
const bool finished = order.state == JobState::Completed;
const auto wood = finished ? rgb(175, 123, 78) : rgb(117, 168, 181);
const auto detail = finished
? (fixture == RecipeId::BuildMedicineCabinet ? rgb(169, 214, 183) : rgb(153, 166, 172))
: rgb(158, 202, 209);
draw_furnishing(mesh, order.position, fixture, wood, detail);
} else if (order.recipe == RecipeId::BuildBed &&
(order.state == JobState::Completed || order.bed_stage == BedStage::Bedding || order.bed_stage == BedStage::Pillow)) {
mesh.box(x, y, .045f, .77f, .43f, .18f,
order.bed_base == BedBase::Stone ? rgb(145, 155, 151) : rgb(156, 107, 66));
if (order.bed_stage == BedStage::Pillow || order.state == JobState::Completed) {
mesh.box(x, y, .225f, .69f, .38f, .12f, rgb(115, 159, 185));
}
if (order.state == JobState::Completed) {
mesh.box(x - .23f, y, .345f, .2f, .32f, .07f, rgb(243, 230, 194));
}
} else if (order.recipe == RecipeId::BuildBed) {
draw_blueprint(mesh, {order.position, order.recipe, order.bed_base}, false);
} else if (order.recipe == RecipeId::BuildCabin && order.state == JobState::Completed) {
const float walls = building_view == BuildingView::FloorsOnly ? .07f : .65f;
mesh.box(x, y, .03f, .83f, .82f, walls, rgb(194, 151, 103));
if (building_view == BuildingView::Full) {
draw_gabled_roof(mesh, x - .415f, y - .41f, x + .415f, y + .41f,
.68f, 1.03f, true, rgb(159, 90, 66), rgb(174, 126, 80));
}
}
}
if (building_view == BuildingView::Full) draw_room_roofs(mesh, world);
for (const auto& job : world.jobs()) {
if (job.state == JobState::Completed) continue;
const float x = static_cast<float>(job.position.x), y = static_cast<float>(job.position.y);
mesh.box(x, y, .015f, .20f, .20f, .10f,
job.state == JobState::Available ? rgb(76, 134, 90) : rgb(208, 159, 77));
}
}
void draw_blueprint(Mesh& mesh, const BlueprintPart& part, bool preview) {
const float x = static_cast<float>(part.cell.x), y = static_cast<float>(part.cell.y);
const auto ink = preview ? rgb(168, 232, 243) : rgb(90, 189, 236);
const auto frame = part.recipe == RecipeId::BuildBed && part.base == BedBase::Stone
? shade(ink, .70f) : ink;
constexpr float beam = .055f;
const auto outline = [&](float width, float depth, float z, Color color) {
for (float side : {-1.f, 1.f}) {
mesh.box(x, y + side * depth / 2, z, width + beam, beam, beam, color);
mesh.box(x + side * width / 2, y, z, beam, depth, beam, color);
}
};
outline(.88f, .88f, .035f, ink);
const float width = part.recipe == RecipeId::BuildBed ? .72f : .70f;
const float depth = part.recipe == RecipeId::BuildBed ? .41f : .62f;
const float top = part.recipe == RecipeId::BuildBed ? .34f : .68f;
outline(width, depth, top, frame);
for (float side_x : {-1.f, 1.f}) {
for (float side_y : {-1.f, 1.f}) {
mesh.box(x + side_x * width / 2, y + side_y * depth / 2, .04f, beam, beam, top - .04f, frame);
}
}
if (part.recipe == RecipeId::WeaveCloth) mesh.box(x, y, .30f, width, beam, beam, ink);
}
void residents(Mesh& mesh, const World& world, const SceneView& view) {
for (const auto& agent : world.agents()) {
using enum AgentState;
if (agent.state != Sleeping) {
auto position = agent.position;
const auto trail = agent.state == Hauling ? rgb(104, 164, 159) : rgb(137, 126, 167);
for (std::size_t i = agent.route_cursor; i < agent.route.size(); ++i) {
mesh.track(position, agent.route[i], trail);
position = agent.route[i];
}
}
const float shift = static_cast<float>(static_cast<int>(agent.id % 5) - 2) / 12.f;
const float x = static_cast<float>(agent.position.x) + shift;
const float y = static_cast<float>(agent.position.y) - shift;
const auto clothes = agent.state == Working ? rgb(195, 98, 74) :
agent.state == Gathering ? rgb(196, 152, 74) :
agent.state == Hauling ? rgb(67, 146, 138) : rgb(89, 126, 172);
if (view.selected == agent.id) {
mesh.flat(x - .28f, y - .26f, x + .28f, y + .26f, .042f, rgb(247, 207, 114));
}
if (agent.state == Sleeping) {
const float bed_height = agent.resting_on_ground ? .035f : .36f;
mesh.box(x, y, bed_height, .54f, .25f, .14f, clothes);
mesh.box(x - .23f, y, bed_height + .01f, .16f, .20f, .15f, rgb(234, 195, 149));
continue;
}
mesh.box(x, y, .027f, .19f, .22f, .14f, rgb(75, 72, 71));
mesh.box(x, y, .167f, .27f, .22f, .22f, clothes);
mesh.box(x, y, .387f, .25f, .24f, .23f, rgb(232, 191, 144));
mesh.box(x - .025f, y - .02f, .59f, .27f, .25f, .065f, rgb(92, 73, 56));
if (is_carpentry_item(agent.inventory.first_item())) {
mesh.box(x - .14f, y - .12f, .09f, .13f, .30f, .39f, rgb(177, 116, 70));
} else if (!agent.inventory.empty()) {
mesh.box(x - .11f, y - .12f, .14f, .19f, .18f, .24f, rgb(200, 156, 92));
}
}
}
constexpr char hlsl[] = R"(
cbuffer Camera : register(b0) {
float2 origin;
float2 halfTile;
float2 screen;
float scale;
float padding;
};
struct Input { float3 position : POSITION; float3 color : COLOR; };
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
Pixel project(Input input) {
float3 p = input.position;
float2 screenPoint = origin + scale * float2((p.x - p.y) * halfTile.x,
(p.x + p.y) * halfTile.y - p.z * 16.0);
Pixel result;
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
result.color = input.color;
return result;
}
float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
)";
} // namespace
struct D3DScene::Backend {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
ComPtr<IDXGISwapChain> swap_chain;
ComPtr<ID3D11Texture2D> target_texture;
ComPtr<ID3D11RenderTargetView> target_view;
ComPtr<ID3D11DepthStencilView> depth_view;
ComPtr<ID3D11VertexShader> vertex_shader;
ComPtr<ID3D11PixelShader> pixel_shader;
ComPtr<ID3D11InputLayout> layout;
ComPtr<ID3D11RasterizerState> rasterizer;
ComPtr<ID3D11Buffer> camera;
ComPtr<ID3D11Buffer> geometry;
UINT buffer_bytes = 0;
int width = 0, height = 0;
Mesh mesh;
bool resize(int w, int h) {
if (w == width && h == height && target_view && depth_view) return true;
context->OMSetRenderTargets(0, nullptr, nullptr);
target_texture.Reset();
target_view.Reset();
depth_view.Reset();
D3D11_TEXTURE2D_DESC texture{};
texture.Width = static_cast<UINT>(w);
texture.Height = static_cast<UINT>(h);
texture.MipLevels = texture.ArraySize = texture.SampleDesc.Count = 1;
texture.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
texture.BindFlags = D3D11_BIND_RENDER_TARGET;
if (swap_chain) {
if (FAILED(swap_chain->ResizeBuffers(0, texture.Width, texture.Height, DXGI_FORMAT_UNKNOWN, 0)) ||
FAILED(swap_chain->GetBuffer(0, IID_PPV_ARGS(target_texture.GetAddressOf())))) return false;
} else if (FAILED(device->CreateTexture2D(&texture, nullptr, &target_texture))) {
return false;
}
texture.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
texture.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ComPtr<ID3D11Texture2D> depth;
if (FAILED(device->CreateRenderTargetView(target_texture.Get(), nullptr, &target_view)) ||
FAILED(device->CreateTexture2D(&texture, nullptr, &depth)) ||
FAILED(device->CreateDepthStencilView(depth.Get(), nullptr, &depth_view))) return false;
width = w;
height = h;
return true;
}
bool upload_geometry() {
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
if (bytes > std::numeric_limits<UINT>::max()) return false;
if (bytes > buffer_bytes) {
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = static_cast<UINT>(bytes);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
buffer_bytes = desc.ByteWidth;
}
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
context->Unmap(geometry.Get(), 0);
return true;
}
bool read_frame(std::vector<std::uint32_t>& pixels) {
D3D11_TEXTURE2D_DESC desc{};
target_texture->GetDesc(&desc);
desc.BindFlags = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
ComPtr<ID3D11Texture2D> copy;
if (FAILED(device->CreateTexture2D(&desc, nullptr, &copy))) return false;
context->CopyResource(copy.Get(), target_texture.Get());
pixels.resize(static_cast<std::size_t>(width) * static_cast<std::size_t>(height));
D3D11_MAPPED_SUBRESOURCE mapped{};
if (FAILED(context->Map(copy.Get(), 0, D3D11_MAP_READ, 0, &mapped))) return false;
const auto* data = static_cast<const std::byte*>(mapped.pData);
for (int row = 0; row < height; ++row) {
std::memcpy(pixels.data() + static_cast<std::size_t>(row) * static_cast<std::size_t>(width),
data + static_cast<std::size_t>(row) * mapped.RowPitch,
static_cast<std::size_t>(width) * sizeof(std::uint32_t));
}
context->Unmap(copy.Get(), 0);
return true;
}
};
D3DScene::D3DScene() = default;
D3DScene::~D3DScene() = default;
bool D3DScene::initialize(HWND target, bool software) {
auto graphics = std::make_unique<Backend>();
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
if (target) {
DXGI_SWAP_CHAIN_DESC swap{};
swap.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
swap.SampleDesc.Count = 1;
swap.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap.BufferCount = 2;
swap.OutputWindow = target;
swap.Windowed = TRUE;
swap.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
if (FAILED(D3D11CreateDeviceAndSwapChain(nullptr, driver, nullptr, flags, levels, std::size(levels),
D3D11_SDK_VERSION, &swap, &graphics->swap_chain, &graphics->device, nullptr, &graphics->context))) return false;
} else if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, flags, levels, std::size(levels),
D3D11_SDK_VERSION, &graphics->device, nullptr, &graphics->context))) return false;
ComPtr<ID3DBlob> vertex, pixel;
constexpr UINT compile_flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3;
if (FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "project", "vs_4_0",
compile_flags, 0, &vertex, nullptr)) ||
FAILED(D3DCompile(hlsl, sizeof(hlsl) - 1, nullptr, nullptr, nullptr, "paint", "ps_4_0",
compile_flags, 0, &pixel, nullptr))) return false;
if (FAILED(graphics->device->CreateVertexShader(vertex->GetBufferPointer(), vertex->GetBufferSize(),
nullptr, &graphics->vertex_shader)) ||
FAILED(graphics->device->CreatePixelShader(pixel->GetBufferPointer(), pixel->GetBufferSize(),
nullptr, &graphics->pixel_shader))) return false;
constexpr D3D11_INPUT_ELEMENT_DESC elements[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(Point), D3D11_INPUT_PER_VERTEX_DATA, 0}
};
D3D11_RASTERIZER_DESC raster{};
raster.FillMode = D3D11_FILL_SOLID;
raster.CullMode = D3D11_CULL_NONE;
raster.DepthClipEnable = TRUE;
D3D11_BUFFER_DESC constants{};
constants.ByteWidth = 32;
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
vertex->GetBufferSize(), &graphics->layout)) ||
FAILED(graphics->device->CreateRasterizerState(&raster, &graphics->rasterizer)) ||
FAILED(graphics->device->CreateBuffer(&constants, nullptr, &graphics->camera))) return false;
backend_ = std::move(graphics);
return true;
}
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
void D3DScene::reset() noexcept { backend_.reset(); }
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *backend_;
if (!graphics.resize(view.width, view.height)) return false;
graphics.mesh.vertices.clear();
terrain(graphics.mesh, world, view);
resources(graphics.mesh, world);
construction(graphics.mesh, world, view.building_view);
for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) {
if (view.moving_room == index) continue;
const auto& plan = view.room_blueprints[index];
draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
}
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
residents(graphics.mesh, world, view);
if (!graphics.upload_geometry()) return false;
auto* ctx = graphics.context.Get();
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
ctx->ClearRenderTargetView(graphics.target_view.Get(), clear);
ctx->ClearDepthStencilView(graphics.depth_view.Get(), D3D11_CLEAR_DEPTH, 1.f, 0);
ctx->OMSetRenderTargets(1, graphics.target_view.GetAddressOf(), graphics.depth_view.Get());
const D3D11_VIEWPORT viewport{0, 0, static_cast<float>(view.width), static_cast<float>(view.height), 0, 1};
ctx->RSSetViewports(1, &viewport);
ctx->RSSetState(graphics.rasterizer.Get());
const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height,
viewport.Width, viewport.Height, view.scale, 0};
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
constexpr UINT stride = sizeof(Vertex);
constexpr UINT offset = 0;
ctx->IASetInputLayout(graphics.layout.Get());
ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ctx->IASetVertexBuffers(0, 1, graphics.geometry.GetAddressOf(), &stride, &offset);
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
if (capture && !graphics.read_frame(*capture)) return false;
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
}
} // namespace settlement::viewer