spriteAPI.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. #include "spriteAPI.h"
  2. #include "Octree.h"
  3. #include "DirtyRectangles.h"
  4. #include "../../../DFPSR/render/ITriangle2D.h"
  5. // Comment out a flag to disable an optimization when debugging
  6. #define DIRTY_RECTANGLE_OPTIMIZATION
  7. namespace dsr {
  8. struct SpriteConfig {
  9. int centerX, centerY; // The sprite's origin in pixels relative to the upper left corner
  10. int frameRows; // The atlas has one row for each frame
  11. int propertyColumns; // The atlas has one column for each type of information
  12. // The 3D model's bound in tile units
  13. // The height image goes from 0 at minimum Y to 255 at maximum Y
  14. FVector3D minBound, maxBound;
  15. // Shadow shapes
  16. List<FVector3D> points; // 3D points for the triangles to refer to by index
  17. List<int32_t> triangleIndices; // Triangle indices stored in multiples of three integers
  18. // Construction
  19. SpriteConfig(int centerX, int centerY, int frameRows, int propertyColumns, FVector3D minBound, FVector3D maxBound)
  20. : centerX(centerX), centerY(centerY), frameRows(frameRows), propertyColumns(propertyColumns), minBound(minBound), maxBound(maxBound) {}
  21. explicit SpriteConfig(const ReadableString& content) {
  22. config_parse_ini(content, [this](const ReadableString& block, const ReadableString& key, const ReadableString& value) {
  23. if (string_length(block) == 0) {
  24. if (string_caseInsensitiveMatch(key, U"CenterX")) {
  25. this->centerX = string_toInteger(value);
  26. } else if (string_caseInsensitiveMatch(key, U"CenterY")) {
  27. this->centerY = string_toInteger(value);
  28. } else if (string_caseInsensitiveMatch(key, U"FrameRows")) {
  29. this->frameRows = string_toInteger(value);
  30. } else if (string_caseInsensitiveMatch(key, U"PropertyColumns")) {
  31. this->propertyColumns = string_toInteger(value);
  32. } else if (string_caseInsensitiveMatch(key, U"MinBound")) {
  33. this->minBound = parseFVector3D(value);
  34. } else if (string_caseInsensitiveMatch(key, U"MaxBound")) {
  35. this->maxBound = parseFVector3D(value);
  36. } else if (string_caseInsensitiveMatch(key, U"Points")) {
  37. List<String> values = string_split(value, U',');
  38. if (values.length() % 3 != 0) {
  39. throwError("Points contained ", values.length(), " values, which is not evenly divisible by three!");
  40. } else {
  41. this->points.clear();
  42. this->points.reserve(values.length() / 3);
  43. for (int v = 0; v < values.length(); v += 3) {
  44. this->points.push(FVector3D(string_toDouble(values[v]), string_toDouble(values[v+1]), string_toDouble(values[v+2])));
  45. }
  46. }
  47. } else if (string_caseInsensitiveMatch(key, U"TriangleIndices")) {
  48. List<String> values = string_split(value, U',');
  49. if (values.length() % 3 != 0) {
  50. throwError("TriangleIndices contained ", values.length(), " values, which is not evenly divisible by three!");
  51. } else {
  52. this->triangleIndices.clear();
  53. this->triangleIndices.reserve(values.length());
  54. for (int v = 0; v < values.length(); v++) {
  55. this->triangleIndices.push(string_toInteger(values[v]));
  56. }
  57. }
  58. } else {
  59. printText("Unrecognized key \"", key, "\" in sprite configuration file.\n");
  60. }
  61. } else {
  62. printText("Unrecognized block \"", block, "\" in sprite configuration file.\n");
  63. }
  64. });
  65. }
  66. // Add model as a persistent shadow caster in the sprite configuration
  67. void appendShadow(const Model& model) {
  68. points.reserve(this->points.length() + model_getNumberOfPoints(model));
  69. for (int p = 0; p < model_getNumberOfPoints(model); p++) {
  70. this->points.push(model_getPoint(model, p));
  71. }
  72. for (int part = 0; part < model_getNumberOfParts(model); part++) {
  73. for (int poly = 0; poly < model_getNumberOfPolygons(model, part); poly++) {
  74. int vertexCount = model_getPolygonVertexCount(model, part, poly);
  75. int vertA = 0;
  76. int indexA = model_getVertexPointIndex(model, part, poly, vertA);
  77. for (int vertB = 1; vertB < vertexCount - 1; vertB++) {
  78. int vertC = vertB + 1;
  79. int indexB = model_getVertexPointIndex(model, part, poly, vertB);
  80. int indexC = model_getVertexPointIndex(model, part, poly, vertC);
  81. triangleIndices.push(indexA); triangleIndices.push(indexB); triangleIndices.push(indexC);
  82. }
  83. }
  84. }
  85. }
  86. String toIni() {
  87. // General information
  88. String result = string_combine(
  89. U"; Sprite configuration file\n",
  90. U"CenterX=", this->centerX, "\n",
  91. U"CenterY=", this->centerY, "\n",
  92. U"FrameRows=", this->frameRows, "\n",
  93. U"PropertyColumns=", this->propertyColumns, "\n",
  94. U"MinBound=", this->minBound, "\n",
  95. U"MaxBound=", this->maxBound, "\n"
  96. );
  97. // Low-resolution 3D shape
  98. if (this->points.length() > 0) {
  99. string_append(result, U"Points=");
  100. for (int p = 0; p < this->points.length(); p++) {
  101. if (p > 0) {
  102. string_append(result, U", ");
  103. }
  104. string_append(result, this->points[p]);
  105. }
  106. string_append(result, U"\n");
  107. string_append(result, U"TriangleIndices=");
  108. for (int i = 0; i < this->triangleIndices.length(); i+=3) {
  109. if (i > 0) {
  110. string_append(result, U", ");
  111. }
  112. string_append(result, this->triangleIndices[i], U",", this->triangleIndices[i+1], U",", this->triangleIndices[i+2]);
  113. }
  114. string_append(result, U"\n");
  115. }
  116. return result;
  117. }
  118. };
  119. static ImageF32 scaleHeightImage(const ImageRgbaU8& heightImage, float minHeight, float maxHeight, const ImageRgbaU8& colorImage) {
  120. float scale = (maxHeight - minHeight) / 255.0f;
  121. float offset = minHeight;
  122. int width = image_getWidth(heightImage);
  123. int height = image_getHeight(heightImage);
  124. ImageF32 result = image_create_F32(width, height);
  125. for (int y = 0; y < height; y++) {
  126. for (int x = 0; x < width; x++) {
  127. float value = image_readPixel_clamp(heightImage, x, y).red;
  128. if (image_readPixel_clamp(colorImage, x, y).alpha > 127) {
  129. image_writePixel(result, x, y, (value * scale) + offset);
  130. } else {
  131. image_writePixel(result, x, y, -std::numeric_limits<float>::infinity());
  132. }
  133. }
  134. }
  135. return result;
  136. }
  137. struct SpriteFrame {
  138. IVector2D centerPoint;
  139. ImageRgbaU8 colorImage; // (Red, Green, Blue, _)
  140. ImageRgbaU8 normalImage; // (NormalX, NormalY, NormalZ, _)
  141. ImageF32 heightImage;
  142. SpriteFrame(const IVector2D& centerPoint, const ImageRgbaU8& colorImage, const ImageRgbaU8& normalImage, const ImageF32& heightImage)
  143. : centerPoint(centerPoint), colorImage(colorImage), normalImage(normalImage), heightImage(heightImage) {}
  144. };
  145. struct SpriteType {
  146. public:
  147. IVector3D minBoundMini, maxBoundMini;
  148. List<SpriteFrame> frames;
  149. // TODO: Compress the data using a shadow-only model type of only positions and triangle indices in a single part.
  150. // The shadow model will have its own rendering method excluding the color target.
  151. // Shadow rendering can be a lot simpler by not calculating any vertex weights
  152. // just interpolate the depth using addition, compare to the old value and write the new depth value.
  153. Model shadowModel;
  154. public:
  155. // folderPath should end with a path separator
  156. SpriteType(const String& folderPath, const String& spriteName) {
  157. // Load the image atlas
  158. ImageRgbaU8 loadedAtlas = image_load_RgbaU8(string_combine(folderPath, spriteName, U".png"));
  159. // Load the settings
  160. const SpriteConfig configuration = SpriteConfig(string_load(string_combine(folderPath, spriteName, U".ini")));
  161. this->minBoundMini = IVector3D(
  162. floor(configuration.minBound.x * ortho_miniUnitsPerTile),
  163. floor(configuration.minBound.y * ortho_miniUnitsPerTile),
  164. floor(configuration.minBound.z * ortho_miniUnitsPerTile)
  165. );
  166. this->maxBoundMini = IVector3D(
  167. ceil(configuration.maxBound.x * ortho_miniUnitsPerTile),
  168. ceil(configuration.maxBound.y * ortho_miniUnitsPerTile),
  169. ceil(configuration.maxBound.z * ortho_miniUnitsPerTile)
  170. );
  171. int width = image_getWidth(loadedAtlas) / configuration.propertyColumns;
  172. int height = image_getHeight(loadedAtlas) / configuration.frameRows;
  173. for (int a = 0; a < configuration.frameRows; a++) {
  174. ImageRgbaU8 colorImage = image_getSubImage(loadedAtlas, IRect(0, a * height, width, height));
  175. ImageRgbaU8 heightImage = image_getSubImage(loadedAtlas, IRect(width, a * height, width, height));
  176. ImageRgbaU8 normalImage = image_getSubImage(loadedAtlas, IRect(width * 2, a * height, width, height));
  177. ImageF32 scaledHeightImage = scaleHeightImage(heightImage, configuration.minBound.y, configuration.maxBound.y, colorImage);
  178. this->frames.pushConstruct(IVector2D(configuration.centerX, configuration.centerY), colorImage, normalImage, scaledHeightImage);
  179. }
  180. // Create a model for rendering shadows
  181. if (configuration.points.length() > 0) {
  182. this->shadowModel = model_create();
  183. for (int p = 0; p < configuration.points.length(); p++) {
  184. model_addPoint(this->shadowModel, configuration.points[p]);
  185. }
  186. model_addEmptyPart(this->shadowModel, U"Shadow");
  187. for (int t = 0; t < configuration.triangleIndices.length(); t+=3) {
  188. model_addTriangle(this->shadowModel, 0, configuration.triangleIndices[t], configuration.triangleIndices[t+1], configuration.triangleIndices[t+2]);
  189. }
  190. }
  191. }
  192. public:
  193. // TODO: Force frame count to a power of two or replace modulo with look-up tables in sprite configurations.
  194. int getFrameIndex(Direction direction) {
  195. const int frameFromDir[dir360] = {4, 1, 5, 2, 6, 3, 7, 0};
  196. return frameFromDir[correctDirection(direction)] % this->frames.length();
  197. }
  198. };
  199. // Global list of all sprite types ever loaded
  200. List<SpriteType> types;
  201. static int getSpriteFrameIndex(const Sprite& sprite, OrthoView view) {
  202. return types[sprite.typeIndex].getFrameIndex(view.worldDirection + sprite.direction);
  203. }
  204. // Returns a 2D bounding box of affected target pixels
  205. IRect drawSprite(const Sprite& sprite, const OrthoView& ortho, const IVector2D& worldCenter, ImageF32 targetHeight, ImageRgbaU8 targetColor, ImageRgbaU8 targetNormal) {
  206. int frameIndex = getSpriteFrameIndex(sprite, ortho);
  207. const SpriteFrame* frame = &types[sprite.typeIndex].frames[frameIndex];
  208. IVector2D screenSpace = ortho.miniTilePositionToScreenPixel(sprite.location, worldCenter) - frame->centerPoint;
  209. float heightOffset = sprite.location.y * ortho_tilesPerMiniUnit;
  210. if (image_exists(targetColor)) {
  211. if (image_exists(targetNormal)) {
  212. draw_higher(targetHeight, frame->heightImage, targetColor, frame->colorImage, targetNormal, frame->normalImage, screenSpace.x, screenSpace.y, heightOffset);
  213. } else {
  214. draw_higher(targetHeight, frame->heightImage, targetColor, frame->colorImage, screenSpace.x, screenSpace.y, heightOffset);
  215. }
  216. } else {
  217. if (image_exists(targetNormal)) {
  218. draw_higher(targetHeight, frame->heightImage, targetNormal, frame->normalImage, screenSpace.x, screenSpace.y, heightOffset);
  219. } else {
  220. draw_higher(targetHeight, frame->heightImage, screenSpace.x, screenSpace.y, heightOffset);
  221. }
  222. }
  223. return IRect(screenSpace.x, screenSpace.y, image_getWidth(frame->colorImage), image_getHeight(frame->colorImage));
  224. }
  225. // The camera transform for each direction
  226. FMatrix3x3 ShadowCubeMapSides[6] = {
  227. FMatrix3x3::makeAxisSystem(FVector3D( 1.0f, 0.0f, 0.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  228. FMatrix3x3::makeAxisSystem(FVector3D(-1.0f, 0.0f, 0.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  229. FMatrix3x3::makeAxisSystem(FVector3D( 0.0f, 1.0f, 0.0f), FVector3D(0.0f, 0.0f, 1.0f)),
  230. FMatrix3x3::makeAxisSystem(FVector3D( 0.0f,-1.0f, 0.0f), FVector3D(0.0f, 0.0f, 1.0f)),
  231. FMatrix3x3::makeAxisSystem(FVector3D( 0.0f, 0.0f, 1.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  232. FMatrix3x3::makeAxisSystem(FVector3D( 0.0f, 0.0f,-1.0f), FVector3D(0.0f, 1.0f, 0.0f))
  233. };
  234. // TODO: Move to the ortho API using a safe getter in modulo
  235. FMatrix3x3 spriteDirections[8] = {
  236. FMatrix3x3::makeAxisSystem(FVector3D( 0.0f, 0.0f, 1.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  237. FMatrix3x3::makeAxisSystem(FVector3D( 1.0f, 0.0f, 1.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  238. FMatrix3x3::makeAxisSystem(FVector3D( 1.0f, 0.0f, 0.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  239. FMatrix3x3::makeAxisSystem(FVector3D( 1.0f, 0.0f,-1.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  240. FMatrix3x3::makeAxisSystem(FVector3D( 0.0f, 0.0f,-1.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  241. FMatrix3x3::makeAxisSystem(FVector3D(-1.0f, 0.0f,-1.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  242. FMatrix3x3::makeAxisSystem(FVector3D(-1.0f, 0.0f, 0.0f), FVector3D(0.0f, 1.0f, 0.0f)),
  243. FMatrix3x3::makeAxisSystem(FVector3D(-1.0f, 0.0f, 1.0f), FVector3D(0.0f, 1.0f, 0.0f))
  244. };
  245. struct CubeMapF32 {
  246. int resolution; // The width and height of each shadow depth image or 0 if no shadows are casted
  247. AlignedImageF32 cubeMap; // A vertical sequence of reciprocal depth images for the six sides of the cube
  248. ImageF32 cubeMapViews[6]; // Sub-images sharing their allocations with cubeMap as sub-images
  249. explicit CubeMapF32(int resolution) : resolution(resolution) {
  250. this->cubeMap = image_create_F32(resolution, resolution * 6);
  251. for (int s = 0; s < 6; s++) {
  252. this->cubeMapViews[s] = image_getSubImage(this->cubeMap, IRect(0, s * resolution, resolution, resolution));
  253. }
  254. }
  255. void clear() {
  256. image_fill(this->cubeMap, 0.0f);
  257. }
  258. };
  259. class PointLight {
  260. public:
  261. FVector3D position; // The world-space center in tile units
  262. float radius; // The light radius in tile units
  263. float intensity; // The color's brightness multiplier (using float to allow smooth fading)
  264. ColorRgbI32 color; // The color of the light (using integers to detect when the color is uniform)
  265. bool shadowCasting; // Casting shadows when enabled
  266. public:
  267. PointLight(FVector3D position, float radius, float intensity, ColorRgbI32 color, bool shadowCasting)
  268. : position(position), radius(radius), intensity(intensity), color(color), shadowCasting(shadowCasting) {}
  269. public:
  270. void renderSpriteShadow(CubeMapF32& shadowTarget, const Sprite& sprite, const FMatrix3x3& normalToWorld) const {
  271. if (sprite.shadowCasting) {
  272. Model model = types[sprite.typeIndex].shadowModel;
  273. if (model_exists(model)) {
  274. // Place the model relative to the light source's position, to make rendering in light-space easier
  275. Transform3D modelToWorldTransform = Transform3D(ortho_miniToFloatingTile(sprite.location) - this->position, spriteDirections[sprite.direction]);
  276. for (int s = 0; s < 6; s++) {
  277. Camera camera = Camera::createPerspective(Transform3D(FVector3D(), ShadowCubeMapSides[s] * normalToWorld), shadowTarget.resolution, shadowTarget.resolution);
  278. model_renderDepth(model, modelToWorldTransform, shadowTarget.cubeMapViews[s], camera);
  279. }
  280. }
  281. }
  282. }
  283. void renderSpriteShadows(CubeMapF32& shadowTarget, Octree<Sprite>& sprites, const FMatrix3x3& normalToWorld) const {
  284. IVector3D center = ortho_floatingTileToMini(this->position);
  285. IVector3D minBound = center - ortho_floatingTileToMini(radius);
  286. IVector3D maxBound = center + ortho_floatingTileToMini(radius);
  287. sprites.map(minBound, maxBound, [this, shadowTarget, normalToWorld](Sprite& sprite, const IVector3D origin, const IVector3D minBound, const IVector3D maxBound) mutable {
  288. this->renderSpriteShadow(shadowTarget, sprite, normalToWorld);
  289. });
  290. }
  291. public:
  292. void illuminate(const OrthoView& camera, const IVector2D& worldCenter, OrderedImageRgbaU8& lightBuffer, const OrderedImageRgbaU8& normalBuffer, const AlignedImageF32& heightBuffer, const CubeMapF32& shadowSource) const {
  293. if (this->shadowCasting) {
  294. addPointLight(camera, worldCenter, lightBuffer, normalBuffer, heightBuffer, this->position, this->radius, this->intensity, this->color, shadowSource.cubeMap);
  295. } else {
  296. addPointLight(camera, worldCenter, lightBuffer, normalBuffer, heightBuffer, this->position, this->radius, this->intensity, this->color);
  297. }
  298. }
  299. };
  300. class DirectedLight {
  301. public:
  302. FVector3D direction; // The world-space direction
  303. float intensity; // The color's brightness multiplier (using float to allow smooth fading)
  304. ColorRgbI32 color; // The color of the light (using integers to detect when the color is uniform)
  305. public:
  306. DirectedLight(FVector3D direction, float intensity, ColorRgbI32 color)
  307. : direction(direction), intensity(intensity), color(color) {}
  308. public:
  309. void illuminate(const OrthoView& camera, const IVector2D& worldCenter, OrderedImageRgbaU8& lightBuffer, const OrderedImageRgbaU8& normalBuffer, bool overwrite = false) const {
  310. if (overwrite) {
  311. setDirectedLight(camera, lightBuffer, normalBuffer, this->direction, this->intensity, this->color);
  312. } else {
  313. addDirectedLight(camera, lightBuffer, normalBuffer, this->direction, this->intensity, this->color);
  314. }
  315. }
  316. };
  317. // BlockState keeps track of when the background itself needs to update from static objects being created or destroyed
  318. enum class BlockState {
  319. Unused,
  320. Ready,
  321. Dirty
  322. };
  323. class BackgroundBlock {
  324. public:
  325. static const int blockSize = 512;
  326. static const int maxDistance = blockSize * 2;
  327. IRect worldRegion;
  328. int cameraId = 0;
  329. BlockState state = BlockState::Unused;
  330. OrderedImageRgbaU8 diffuseBuffer;
  331. OrderedImageRgbaU8 normalBuffer;
  332. AlignedImageF32 heightBuffer;
  333. private:
  334. IVector3D getBoxCorner(const IVector3D& minBound, const IVector3D& maxBound, int cornerIndex) {
  335. assert(cornerIndex >= 0 && cornerIndex < 8);
  336. return IVector3D(
  337. ((uint32_t)cornerIndex & 1u) ? maxBound.x : minBound.x,
  338. ((uint32_t)cornerIndex & 2u) ? maxBound.y : minBound.y,
  339. ((uint32_t)cornerIndex & 4u) ? maxBound.z : minBound.z
  340. );
  341. }
  342. // Pre-condition: diffuseBuffer must be cleared unless sprites cover the whole block
  343. void draw(Octree<Sprite>& sprites, const OrthoView& ortho) {
  344. image_fill(this->normalBuffer, ColorRgbaI32(128));
  345. image_fill(this->heightBuffer, -std::numeric_limits<float>::max());
  346. sprites.map(
  347. [ortho,this](const IVector3D& minBound, const IVector3D& maxBound){
  348. IVector2D corners[8];
  349. for (int c = 0; c < 8; c++) {
  350. corners[c] = ortho.miniTileOffsetToScreenPixel(getBoxCorner(minBound, maxBound, c));
  351. }
  352. if (corners[0].x < this->worldRegion.left()
  353. && corners[1].x < this->worldRegion.left()
  354. && corners[2].x < this->worldRegion.left()
  355. && corners[3].x < this->worldRegion.left()
  356. && corners[4].x < this->worldRegion.left()
  357. && corners[5].x < this->worldRegion.left()
  358. && corners[6].x < this->worldRegion.left()
  359. && corners[7].x < this->worldRegion.left()) {
  360. return false;
  361. }
  362. if (corners[0].x > this->worldRegion.right()
  363. && corners[1].x > this->worldRegion.right()
  364. && corners[2].x > this->worldRegion.right()
  365. && corners[3].x > this->worldRegion.right()
  366. && corners[4].x > this->worldRegion.right()
  367. && corners[5].x > this->worldRegion.right()
  368. && corners[6].x > this->worldRegion.right()
  369. && corners[7].x > this->worldRegion.right()) {
  370. return false;
  371. }
  372. if (corners[0].y < this->worldRegion.top()
  373. && corners[1].y < this->worldRegion.top()
  374. && corners[2].y < this->worldRegion.top()
  375. && corners[3].y < this->worldRegion.top()
  376. && corners[4].y < this->worldRegion.top()
  377. && corners[5].y < this->worldRegion.top()
  378. && corners[6].y < this->worldRegion.top()
  379. && corners[7].y < this->worldRegion.top()) {
  380. return false;
  381. }
  382. if (corners[0].y > this->worldRegion.bottom()
  383. && corners[1].y > this->worldRegion.bottom()
  384. && corners[2].y > this->worldRegion.bottom()
  385. && corners[3].y > this->worldRegion.bottom()
  386. && corners[4].y > this->worldRegion.bottom()
  387. && corners[5].y > this->worldRegion.bottom()
  388. && corners[6].y > this->worldRegion.bottom()
  389. && corners[7].y > this->worldRegion.bottom()) {
  390. return false;
  391. }
  392. return true;
  393. },
  394. [this, ortho](Sprite& sprite, const IVector3D origin, const IVector3D minBound, const IVector3D maxBound){
  395. drawSprite(sprite, ortho, -this->worldRegion.upperLeft(), this->heightBuffer, this->diffuseBuffer, this->normalBuffer);
  396. });
  397. }
  398. public:
  399. BackgroundBlock(Octree<Sprite>& sprites, const IRect& worldRegion, const OrthoView& ortho)
  400. : worldRegion(worldRegion), cameraId(ortho.id), state(BlockState::Ready),
  401. diffuseBuffer(image_create_RgbaU8(blockSize, blockSize)),
  402. normalBuffer(image_create_RgbaU8(blockSize, blockSize)),
  403. heightBuffer(image_create_F32(blockSize, blockSize)) {
  404. this->draw(sprites, ortho);
  405. }
  406. void update(Octree<Sprite>& sprites, const IRect& worldRegion, const OrthoView& ortho) {
  407. this->worldRegion = worldRegion;
  408. this->cameraId = ortho.id;
  409. image_fill(this->diffuseBuffer, ColorRgbaI32(0));
  410. this->draw(sprites, ortho);
  411. this->state = BlockState::Ready;
  412. }
  413. void draw(ImageRgbaU8& diffuseTarget, ImageRgbaU8& normalTarget, ImageF32& heightTarget, const IRect& seenRegion) const {
  414. if (this->state != BlockState::Unused) {
  415. int left = this->worldRegion.left() - seenRegion.left();
  416. int top = this->worldRegion.top() - seenRegion.top();
  417. draw_copy(diffuseTarget, this->diffuseBuffer, left, top);
  418. draw_copy(normalTarget, this->normalBuffer, left, top);
  419. draw_copy(heightTarget, this->heightBuffer, left, top);
  420. }
  421. }
  422. void recycle() {
  423. //printText("Recycle block at ", this->worldRegion, "\n");
  424. this->state = BlockState::Unused;
  425. this->worldRegion = IRect();
  426. this->cameraId = -1;
  427. }
  428. };
  429. // TODO: A way to delete passive sprites using search criterias for bounding box and leaf content using a boolean lambda
  430. class SpriteWorldImpl {
  431. public:
  432. // World
  433. OrthoSystem ortho;
  434. // Sprites that rarely change and can be stored in a background image. (no animations allowed)
  435. // TODO: Don't store the position twice, by keeping it separate from the Sprite struct.
  436. Octree<Sprite> passiveSprites;
  437. // Temporary things are deleted when spriteWorld_clearTemporary is called
  438. List<Sprite> temporarySprites;
  439. List<PointLight> temporaryPointLights;
  440. List<DirectedLight> temporaryDirectedLights;
  441. // View
  442. int cameraIndex = 0;
  443. IVector3D cameraLocation;
  444. // Deferred rendering
  445. OrderedImageRgbaU8 diffuseBuffer;
  446. OrderedImageRgbaU8 normalBuffer;
  447. AlignedImageF32 heightBuffer;
  448. OrderedImageRgbaU8 lightBuffer;
  449. // Passive background
  450. // TODO: How can split-screen use multiple cameras without duplicate blocks or deleting the other camera's blocks by distance?
  451. List<BackgroundBlock> backgroundBlocks;
  452. // These dirty rectangles keep track of when the background has to be redrawn to the screen after having drawn a dynamic sprite, moved the camera or changed static geometry
  453. DirtyRectangles dirtyBackground;
  454. private:
  455. // Reused buffers
  456. int shadowResolution;
  457. CubeMapF32 temporaryShadowMap;
  458. public:
  459. SpriteWorldImpl(const OrthoSystem &ortho, int shadowResolution)
  460. : ortho(ortho), passiveSprites(ortho_miniUnitsPerTile * 64), shadowResolution(shadowResolution), temporaryShadowMap(shadowResolution) {}
  461. public:
  462. void updateBlockAt(const IRect& blockRegion, const IRect& seenRegion) {
  463. int unusedBlockIndex = -1;
  464. // Find an existing block
  465. for (int b = 0; b < this->backgroundBlocks.length(); b++) {
  466. BackgroundBlock* currentBlockPtr = &this->backgroundBlocks[b];
  467. if (currentBlockPtr->state != BlockState::Unused) {
  468. // Check direction
  469. if (currentBlockPtr->cameraId == this->ortho.view[this->cameraIndex].id) {
  470. // Check location
  471. if (currentBlockPtr->worldRegion.left() == blockRegion.left() && currentBlockPtr->worldRegion.top() == blockRegion.top()) {
  472. // Update if needed
  473. if (currentBlockPtr->state == BlockState::Dirty) {
  474. currentBlockPtr->update(this->passiveSprites, blockRegion, this->ortho.view[this->cameraIndex]);
  475. }
  476. // Use the block
  477. return;
  478. } else {
  479. // See if the block is too far from the camera
  480. if (currentBlockPtr->worldRegion.right() < seenRegion.left() - BackgroundBlock::maxDistance
  481. || currentBlockPtr->worldRegion.left() > seenRegion.right() + BackgroundBlock::maxDistance
  482. || currentBlockPtr->worldRegion.bottom() < seenRegion.top() - BackgroundBlock::maxDistance
  483. || currentBlockPtr->worldRegion.top() > seenRegion.bottom() + BackgroundBlock::maxDistance) {
  484. // Recycle because it's too far away
  485. currentBlockPtr->recycle();
  486. unusedBlockIndex = b;
  487. }
  488. }
  489. } else{
  490. // Recycle directly when another camera angle is used
  491. currentBlockPtr->recycle();
  492. unusedBlockIndex = b;
  493. }
  494. } else {
  495. unusedBlockIndex = b;
  496. }
  497. }
  498. // If none of them matched, we should've passed by any unused block already
  499. if (unusedBlockIndex > -1) {
  500. // We have a block to reuse
  501. this->backgroundBlocks[unusedBlockIndex].update(this->passiveSprites, blockRegion, this->ortho.view[this->cameraIndex]);
  502. } else {
  503. // Create a new block
  504. this->backgroundBlocks.pushConstruct(this->passiveSprites, blockRegion, this->ortho.view[this->cameraIndex]);
  505. }
  506. }
  507. void invalidateBlockAt(int left, int top) {
  508. // Find an existing block
  509. for (int b = 0; b < this->backgroundBlocks.length(); b++) {
  510. BackgroundBlock* currentBlockPtr = &this->backgroundBlocks[b];
  511. // Assuming that alternative camera angles will be removed when drawing next time
  512. if (currentBlockPtr->state == BlockState::Ready
  513. && currentBlockPtr->worldRegion.left() == left
  514. && currentBlockPtr->worldRegion.top() == top) {
  515. // Make dirty to force an update
  516. currentBlockPtr->state = BlockState::Dirty;
  517. }
  518. }
  519. }
  520. // Make sure that each pixel in seenRegion is occupied by an updated background block
  521. void updateBlocks(const IRect& seenRegion) {
  522. // Round inclusive pixel indices down to containing blocks and iterate over them in strides along x and y
  523. int64_t roundedLeft = roundDown(seenRegion.left(), BackgroundBlock::blockSize);
  524. int64_t roundedTop = roundDown(seenRegion.top(), BackgroundBlock::blockSize);
  525. int64_t roundedRight = roundDown(seenRegion.right() - 1, BackgroundBlock::blockSize);
  526. int64_t roundedBottom = roundDown(seenRegion.bottom() - 1, BackgroundBlock::blockSize);
  527. for (int64_t y = roundedTop; y <= roundedBottom; y += BackgroundBlock::blockSize) {
  528. for (int64_t x = roundedLeft; x <= roundedRight; x += BackgroundBlock::blockSize) {
  529. // Make sure that a block is allocated and pre-drawn at this location
  530. this->updateBlockAt(IRect(x, y, BackgroundBlock::blockSize, BackgroundBlock::blockSize), seenRegion);
  531. }
  532. }
  533. }
  534. void drawDeferred(OrderedImageRgbaU8& diffuseTarget, OrderedImageRgbaU8& normalTarget, AlignedImageF32& heightTarget, const IRect& seenRegion) {
  535. // Check image dimensions
  536. assert(image_getWidth(diffuseTarget) == seenRegion.width() && image_getHeight(diffuseTarget) == seenRegion.height());
  537. assert(image_getWidth(normalTarget) == seenRegion.width() && image_getHeight(normalTarget) == seenRegion.height());
  538. assert(image_getWidth(heightTarget) == seenRegion.width() && image_getHeight(heightTarget) == seenRegion.height());
  539. this->dirtyBackground.setTargetResolution(seenRegion.width(), seenRegion.height());
  540. // Draw passive sprites to blocks
  541. this->updateBlocks(seenRegion);
  542. // Draw background blocks to the target images
  543. for (int b = 0; b < this->backgroundBlocks.length(); b++) {
  544. #ifdef DIRTY_RECTANGLE_OPTIMIZATION
  545. // Optimized version
  546. for (int64_t r = 0; r < this->dirtyBackground.getRectangleCount(); r++) {
  547. IRect screenClip = this->dirtyBackground.getRectangle(r);
  548. IRect worldClip = screenClip + seenRegion.upperLeft();
  549. ImageRgbaU8 clippedDiffuseTarget = image_getSubImage(diffuseTarget, screenClip);
  550. ImageRgbaU8 clippedNormalTarget = image_getSubImage(normalTarget, screenClip);
  551. ImageF32 clippedHeightTarget = image_getSubImage(heightTarget, screenClip);
  552. this->backgroundBlocks[b].draw(clippedDiffuseTarget, clippedNormalTarget, clippedHeightTarget, worldClip);
  553. }
  554. #else
  555. // Reference implementation
  556. this->backgroundBlocks[b].draw(diffuseTarget, normalTarget, heightTarget, seenRegion);
  557. #endif
  558. }
  559. // Reset dirty rectangles so that active sprites may record changes
  560. this->dirtyBackground.noneDirty();
  561. // Draw active sprites to the targets
  562. for (int s = 0; s < this->temporarySprites.length(); s++) {
  563. IRect drawnRegion = drawSprite(this->temporarySprites[s], this->ortho.view[this->cameraIndex], -seenRegion.upperLeft(), heightTarget, diffuseTarget, normalTarget);
  564. this->dirtyBackground.makeRegionDirty(drawnRegion);
  565. }
  566. }
  567. public:
  568. void updatePassiveRegion(const IRect& modifiedRegion) {
  569. int64_t roundedLeft = roundDown(modifiedRegion.left(), BackgroundBlock::blockSize);
  570. int64_t roundedTop = roundDown(modifiedRegion.top(), BackgroundBlock::blockSize);
  571. int64_t roundedRight = roundDown(modifiedRegion.right() - 1, BackgroundBlock::blockSize);
  572. int64_t roundedBottom = roundDown(modifiedRegion.bottom() - 1, BackgroundBlock::blockSize);
  573. for (int64_t y = roundedTop; y <= roundedBottom; y += BackgroundBlock::blockSize) {
  574. for (int64_t x = roundedLeft; x <= roundedRight; x += BackgroundBlock::blockSize) {
  575. // Make sure that a block is allocated and pre-drawn at this location
  576. this->invalidateBlockAt(x, y);
  577. }
  578. }
  579. // Redrawing the whole background to the screen is very cheap using memcpy, so no need to optimize this rare event
  580. this->dirtyBackground.allDirty();
  581. }
  582. IVector2D findWorldCenter(const AlignedImageRgbaU8& colorTarget) const {
  583. return IVector2D(image_getWidth(colorTarget) / 2, image_getHeight(colorTarget) / 2) - this->ortho.miniTileOffsetToScreenPixel(this->cameraLocation, this->cameraIndex);
  584. }
  585. void draw(AlignedImageRgbaU8& colorTarget) {
  586. double startTime;
  587. IVector2D worldCenter = this->findWorldCenter(colorTarget);
  588. // Resize when the window has resized or the buffers haven't been allocated before
  589. int width = image_getWidth(colorTarget);
  590. int height = image_getHeight(colorTarget);
  591. if (image_getWidth(this->diffuseBuffer) != width || image_getHeight(this->diffuseBuffer) != height) {
  592. this->diffuseBuffer = image_create_RgbaU8(width, height);
  593. this->normalBuffer = image_create_RgbaU8(width, height);
  594. this->lightBuffer = image_create_RgbaU8(width, height);
  595. this->heightBuffer = image_create_F32(width, height);
  596. }
  597. IRect worldRegion = IRect(-worldCenter.x, -worldCenter.y, width, height);
  598. startTime = time_getSeconds();
  599. this->drawDeferred(this->diffuseBuffer, this->normalBuffer, this->heightBuffer, worldRegion);
  600. debugText("Draw deferred: ", (time_getSeconds() - startTime) * 1000.0, " ms\n");
  601. // Illuminate using directed lights
  602. if (this->temporaryDirectedLights.length() > 0) {
  603. startTime = time_getSeconds();
  604. // Overwriting any light from the previous frame
  605. for (int p = 0; p < this->temporaryDirectedLights.length(); p++) {
  606. this->temporaryDirectedLights[p].illuminate(this->ortho.view[this->cameraIndex], worldCenter, this->lightBuffer, this->normalBuffer, p == 0);
  607. }
  608. debugText("Sun light: ", (time_getSeconds() - startTime) * 1000.0, " ms\n");
  609. } else {
  610. startTime = time_getSeconds();
  611. image_fill(this->lightBuffer, ColorRgbaI32(0)); // Set light to black
  612. debugText("Clear light: ", (time_getSeconds() - startTime) * 1000.0, " ms\n");
  613. }
  614. // Illuminate using point lights
  615. for (int p = 0; p < this->temporaryPointLights.length(); p++) {
  616. PointLight *currentLight = &this->temporaryPointLights[p];
  617. if (currentLight->shadowCasting) {
  618. startTime = time_getSeconds();
  619. this->temporaryShadowMap.clear();
  620. currentLight->renderSpriteShadows(this->temporaryShadowMap, this->passiveSprites, ortho.view[this->cameraIndex].normalToWorldSpace);
  621. for (int s = 0; s < this->temporarySprites.length(); s++) {
  622. currentLight->renderSpriteShadow(this->temporaryShadowMap, this->temporarySprites[s], ortho.view[this->cameraIndex].normalToWorldSpace);
  623. }
  624. debugText("Cast point-light shadows: ", (time_getSeconds() - startTime) * 1000.0, " ms\n");
  625. }
  626. startTime = time_getSeconds();
  627. currentLight->illuminate(this->ortho.view[this->cameraIndex], worldCenter, this->lightBuffer, this->normalBuffer, this->heightBuffer, this->temporaryShadowMap);
  628. debugText("Illuminate from point-light: ", (time_getSeconds() - startTime) * 1000.0, " ms\n");
  629. }
  630. // Draw the final image to the target by multiplying diffuse with light
  631. startTime = time_getSeconds();
  632. blendLight(colorTarget, this->diffuseBuffer, this->lightBuffer);
  633. debugText("Blend light: ", (time_getSeconds() - startTime) * 1000.0, " ms\n");
  634. }
  635. };
  636. int sprite_loadTypeFromFile(const String& folderPath, const String& spriteName) {
  637. types.pushConstruct(folderPath, spriteName);
  638. return types.length() - 1;
  639. }
  640. int sprite_getTypeCount() {
  641. return types.length();
  642. }
  643. SpriteWorld spriteWorld_create(OrthoSystem ortho, int shadowResolution) {
  644. return std::make_shared<SpriteWorldImpl>(ortho, shadowResolution);
  645. }
  646. #define MUST_EXIST(OBJECT, METHOD) if (OBJECT.get() == nullptr) { throwError("The " #OBJECT " handle was null in " #METHOD "\n"); }
  647. void spriteWorld_addBackgroundSprite(SpriteWorld& world, const Sprite& sprite) {
  648. MUST_EXIST(world, spriteWorld_addBackgroundSprite);
  649. // TODO: Validate type index before looking up the bounding box, for easy debugging
  650. // TODO: Replace sprite.location with a separate position argument, possibly constructing in place using the API
  651. // Add the passive sprite to the octree
  652. IVector3D origin = sprite.location;
  653. IVector3D minBound = origin + types[sprite.typeIndex].minBoundMini;
  654. IVector3D maxBound = origin + types[sprite.typeIndex].maxBoundMini;
  655. world->passiveSprites.insert(sprite, origin, minBound, maxBound);
  656. // Find the affected passive region and make it dirty
  657. int frameIndex = getSpriteFrameIndex(sprite, world->ortho.view[world->cameraIndex]);
  658. const SpriteFrame* frame = &types[sprite.typeIndex].frames[frameIndex];
  659. IVector2D upperLeft = world->ortho.miniTilePositionToScreenPixel(sprite.location, world->cameraIndex, IVector2D()) - frame->centerPoint;
  660. IRect region = IRect(upperLeft.x, upperLeft.y, image_getWidth(frame->colorImage), image_getHeight(frame->colorImage));
  661. world->updatePassiveRegion(region);
  662. }
  663. void spriteWorld_addTemporarySprite(SpriteWorld& world, const Sprite& sprite) {
  664. MUST_EXIST(world, spriteWorld_addTemporarySprite);
  665. // Add the temporary sprite
  666. world->temporarySprites.push(sprite);
  667. }
  668. void spriteWorld_createTemporary_pointLight(SpriteWorld& world, const FVector3D position, float radius, float intensity, ColorRgbI32 color, bool shadowCasting) {
  669. MUST_EXIST(world, spriteWorld_createTemporary_pointLight);
  670. world->temporaryPointLights.pushConstruct(position, radius, intensity, color, shadowCasting);
  671. }
  672. void spriteWorld_createTemporary_directedLight(SpriteWorld& world, const FVector3D direction, float intensity, ColorRgbI32 color) {
  673. MUST_EXIST(world, spriteWorld_createTemporary_pointLight);
  674. world->temporaryDirectedLights.pushConstruct(direction, intensity, color);
  675. }
  676. void spriteWorld_clearTemporary(SpriteWorld& world) {
  677. MUST_EXIST(world, spriteWorld_clearTemporary);
  678. world->temporarySprites.clear();
  679. world->temporaryPointLights.clear();
  680. world->temporaryDirectedLights.clear();
  681. }
  682. void spriteWorld_draw(SpriteWorld& world, AlignedImageRgbaU8& colorTarget) {
  683. MUST_EXIST(world, spriteWorld_draw);
  684. world->draw(colorTarget);
  685. }
  686. IVector3D spriteWorld_findGroundAtPixel(SpriteWorld& world, const AlignedImageRgbaU8& colorBuffer, const IVector2D& pixelLocation) {
  687. MUST_EXIST(world, spriteWorld_findGroundAtPixel);
  688. return world->ortho.pixelToMiniPosition(pixelLocation, world->cameraIndex, world->findWorldCenter(colorBuffer));
  689. }
  690. void spriteWorld_moveCameraInPixels(SpriteWorld& world, const IVector2D& pixelOffset) {
  691. MUST_EXIST(world, spriteWorld_moveCameraInPixels);
  692. if (pixelOffset.x != 0 && pixelOffset.y != 0) {
  693. world->cameraLocation = world->cameraLocation + world->ortho.pixelToMiniOffset(pixelOffset, world->cameraIndex);
  694. world->dirtyBackground.allDirty();
  695. }
  696. }
  697. AlignedImageRgbaU8 spriteWorld_getDiffuseBuffer(SpriteWorld& world) {
  698. MUST_EXIST(world, spriteWorld_getDiffuseBuffer);
  699. return world->diffuseBuffer;
  700. }
  701. OrderedImageRgbaU8 spriteWorld_getNormalBuffer(SpriteWorld& world) {
  702. MUST_EXIST(world, spriteWorld_getNormalBuffer);
  703. return world->normalBuffer;
  704. }
  705. OrderedImageRgbaU8 spriteWorld_getLightBuffer(SpriteWorld& world) {
  706. MUST_EXIST(world, spriteWorld_getLightBuffer);
  707. return world->lightBuffer;
  708. }
  709. AlignedImageF32 spriteWorld_getHeightBuffer(SpriteWorld& world) {
  710. MUST_EXIST(world, spriteWorld_getHeightBuffer);
  711. return world->heightBuffer;
  712. }
  713. int spriteWorld_getCameraDirectionIndex(SpriteWorld& world) {
  714. MUST_EXIST(world, spriteWorld_getCameraDirectionIndex);
  715. return world->cameraIndex;
  716. }
  717. void spriteWorld_setCameraDirectionIndex(SpriteWorld& world, int index) {
  718. MUST_EXIST(world, spriteWorld_setCameraDirectionIndex);
  719. if (index != world->cameraIndex) {
  720. world->cameraIndex = index;
  721. world->dirtyBackground.allDirty();
  722. }
  723. }
  724. static FVector3D normalFromPoints(const FVector3D& A, const FVector3D& B, const FVector3D& C) {
  725. return normalize(crossProduct(B - A, C - A));
  726. }
  727. static FVector3D getAverageNormal(const Model& model, int part, int poly) {
  728. int vertexCount = model_getPolygonVertexCount(model, part, poly);
  729. FVector3D normalSum;
  730. for (int t = 0; t < vertexCount - 2; t++) {
  731. normalSum = normalSum + normalFromPoints(
  732. model_getVertexPosition(model, part, poly, 0),
  733. model_getVertexPosition(model, part, poly, t + 1),
  734. model_getVertexPosition(model, part, poly, t + 2)
  735. );
  736. }
  737. return normalize(normalSum);
  738. }
  739. // Pre-conditions:
  740. // * All images must exist and have the same dimensions
  741. // * All triangles in model must be contained within the image bounds after being projected using view
  742. // TODO: Render directly with a location to a 16-bit depth buffer for background 3D models and brush preview
  743. static void sprite_render(Model model, OrthoView view, ImageF32 depthBuffer, ImageRgbaU8 diffuseTarget, ImageRgbaU8 normalTarget) {
  744. int pointCount = model_getNumberOfPoints(model);
  745. IRect clipBound = image_getBound(depthBuffer);
  746. FVector2D projectionOffset = FVector2D((float)clipBound.width() * 0.5f, (float)clipBound.height() * 0.5f);
  747. // TODO: Allow having length 0 for Arrays and Fields by preventing all access to elements in special cases
  748. Array<FVector3D> projectedPoints(pointCount, FVector3D()); // pixel X, pixel Y, mini-tile height
  749. Array<FVector3D> normalPoints(pointCount, FVector3D()); // normal X, Y, Z
  750. // TODO: Store an array of normals for each point, sum normal vectors for each included polygon and normalize the result
  751. // Interpolate and normalize again for each pixel
  752. for (int point = 0; point < pointCount; point++) {
  753. FVector3D projected = view.worldSpaceToScreenDepth.transform(model_getPoint(model, point));
  754. projectedPoints[point] = FVector3D(projected.x + projectionOffset.x, projected.y + projectionOffset.y, projected.z);
  755. }
  756. // Calculate rounded normals in light-space.
  757. // TODO: Pre-generate normals in world space before transforming into light space.
  758. FMatrix3x3 normalToWorldSpace = view.normalToWorldSpace;
  759. for (int part = 0; part < model_getNumberOfParts(model); part++) {
  760. for (int poly = 0; poly < model_getNumberOfPolygons(model, part); poly++) {
  761. // Transform the normal into a coordinate system aligned with the camera.
  762. // Otherwise the rotation cannot be used for individual rotation to have a corner for each wall.
  763. FVector3D worldNormal = getAverageNormal(model, part, poly);
  764. FVector3D localNormal = normalToWorldSpace.transformTransposed(worldNormal);
  765. for (int vert = 0; vert < model_getPolygonVertexCount(model, part, poly); vert++) {
  766. int point = model_getVertexPointIndex(model, part, poly, vert);
  767. normalPoints[point] = normalPoints[point] + localNormal;
  768. }
  769. }
  770. }
  771. for (int point = 0; point < pointCount; point++) {
  772. normalPoints[point] = normalize(normalPoints[point]);
  773. }
  774. // Render polygons as triangle fans
  775. for (int part = 0; part < model_getNumberOfParts(model); part++) {
  776. for (int poly = 0; poly < model_getNumberOfPolygons(model, part); poly++) {
  777. int vertexCount = model_getPolygonVertexCount(model, part, poly);
  778. int vertA = 0;
  779. FVector4D vertexColorA = model_getVertexColor(model, part, poly, vertA) * 255.0f;
  780. int indexA = model_getVertexPointIndex(model, part, poly, vertA);
  781. FVector3D normalA = normalPoints[indexA];
  782. FVector3D pointA = projectedPoints[indexA];
  783. LVector2D subPixelA = LVector2D(safeRoundInt64(pointA.x * constants::unitsPerPixel), safeRoundInt64(pointA.y * constants::unitsPerPixel));
  784. for (int vertB = 1; vertB < vertexCount - 1; vertB++) {
  785. int vertC = vertB + 1;
  786. int indexB = model_getVertexPointIndex(model, part, poly, vertB);
  787. int indexC = model_getVertexPointIndex(model, part, poly, vertC);
  788. FVector4D vertexColorB = model_getVertexColor(model, part, poly, vertB) * 255.0f;
  789. FVector4D vertexColorC = model_getVertexColor(model, part, poly, vertC) * 255.0f;
  790. FVector3D normalB = normalPoints[indexB];
  791. FVector3D normalC = normalPoints[indexC];
  792. FVector3D pointB = projectedPoints[indexB];
  793. FVector3D pointC = projectedPoints[indexC];
  794. LVector2D subPixelB = LVector2D(safeRoundInt64(pointB.x * constants::unitsPerPixel), safeRoundInt64(pointB.y * constants::unitsPerPixel));
  795. LVector2D subPixelC = LVector2D(safeRoundInt64(pointC.x * constants::unitsPerPixel), safeRoundInt64(pointC.y * constants::unitsPerPixel));
  796. IRect triangleBound = IRect::cut(clipBound, getTriangleBound(subPixelA, subPixelB, subPixelC));
  797. int rowCount = triangleBound.height();
  798. if (rowCount > 0) {
  799. // TODO: Fix the excess pixel bugs
  800. RowInterval rows[rowCount];
  801. rasterizeTriangle(subPixelA, subPixelB, subPixelC, rows, triangleBound);
  802. for (int y = triangleBound.top(); y < triangleBound.bottom(); y++) {
  803. int rowIndex = y - triangleBound.top();
  804. int left = rows[rowIndex].left;
  805. int right = rows[rowIndex].right;
  806. for (int x = left; x < right; x++) {
  807. FVector3D weight = getAffineWeight(FVector2D(pointA.x, pointA.y), FVector2D(pointB.x, pointB.y), FVector2D(pointC.x, pointC.y), FVector2D(x + 0.5f, y + 0.5f));
  808. float height = interpolateUsingAffineWeight(pointA.z, pointB.z, pointC.z, weight);
  809. if (height > image_readPixel_clamp(depthBuffer, x, y)) {
  810. FVector4D vertexColor = interpolateUsingAffineWeight(vertexColorA, vertexColorB, vertexColorC, weight);
  811. FVector3D normal = (normalize(interpolateUsingAffineWeight(normalA, normalB, normalC, weight)) + 1.0f) * 127.5f;
  812. image_writePixel(depthBuffer, x, y, height);
  813. image_writePixel(diffuseTarget, x, y, ColorRgbaI32(vertexColor.x, vertexColor.y, vertexColor.z, 255));
  814. image_writePixel(normalTarget, x, y, ColorRgbaI32(normal.x, normal.y, normal.z, 255));
  815. }
  816. }
  817. }
  818. }
  819. }
  820. }
  821. }
  822. }
  823. void sprite_generateFromModel(ImageRgbaU8& targetAtlas, String& targetConfigText, const Model& visibleModel, const Model& shadowModel, const OrthoSystem& ortho, const String& targetPath, int cameraAngles) {
  824. // Validate input
  825. if (cameraAngles < 1) {
  826. printText(" Need at least one camera angle to generate a sprite!\n");
  827. return;
  828. } else if (!model_exists(visibleModel)) {
  829. printText(" There's nothing to render, because visible model does not exist!\n");
  830. return;
  831. } else if (model_getNumberOfParts(visibleModel) == 0) {
  832. printText(" There's nothing to render in the visible model, because there are no parts in the visible model!\n");
  833. return;
  834. } else {
  835. // Measure the bounding cylinder for determining the uncropped image size
  836. FVector3D minBound = FVector3D(std::numeric_limits<float>::max());
  837. FVector3D maxBound = FVector3D(-std::numeric_limits<float>::max());
  838. for (int p = 0; p < model_getNumberOfPoints(visibleModel); p++) {
  839. FVector3D point = model_getPoint(visibleModel, p);
  840. if (point.x < minBound.x) { minBound.x = point.x; }
  841. if (point.y < minBound.y) { minBound.y = point.y; }
  842. if (point.z < minBound.z) { minBound.z = point.z; }
  843. if (point.x > maxBound.x) { maxBound.x = point.x; }
  844. if (point.y > maxBound.y) { maxBound.y = point.y; }
  845. if (point.z > maxBound.z) { maxBound.z = point.z; }
  846. }
  847. // Check if generating a bound failed
  848. if (minBound.x > maxBound.x) {
  849. printText(" There's nothing visible in the model, because the 3D bounding box had no points to be created from!\n");
  850. return;
  851. }
  852. printText(" Representing height from ", minBound.y, " to ", maxBound.y, " encoded using 8-bits\n");
  853. // Calculate initial image size
  854. float worstCaseDiameter = (std::max(maxBound.x, -minBound.x) + std::max(maxBound.y, -minBound.y) + std::max(maxBound.z, -minBound.z)) * 2;
  855. int maxRes = roundUp(worstCaseDiameter * ortho.pixelsPerTile, 2) + 4; // Round up to even pixels and add 4 padding pixels
  856. // Allocate square images from the pessimistic size estimation
  857. int width = maxRes;
  858. int height = maxRes;
  859. ImageF32 depthBuffer = image_create_F32(width, height);
  860. ImageRgbaU8 colorImage[cameraAngles];
  861. ImageRgbaU8 heightImage[cameraAngles];
  862. ImageRgbaU8 normalImage[cameraAngles];
  863. for (int a = 0; a < cameraAngles; a++) {
  864. colorImage[a] = image_create_RgbaU8(width, height);
  865. heightImage[a] = image_create_RgbaU8(width, height);
  866. normalImage[a] = image_create_RgbaU8(width, height);
  867. }
  868. // Render the model to multiple render targets at once
  869. float heightScale = 255.0f / (maxBound.y - minBound.y);
  870. for (int a = 0; a < cameraAngles; a++) {
  871. image_fill(depthBuffer, -1000000000.0f);
  872. image_fill(colorImage[a], ColorRgbaI32(0, 0, 0, 0));
  873. sprite_render(visibleModel, ortho.view[a], depthBuffer, colorImage[a], normalImage[a]);
  874. // Convert height into an 8 bit channel for saving
  875. for (int y = 0; y < height; y++) {
  876. for (int x = 0; x < width; x++) {
  877. int32_t opacityPixel = image_readPixel_clamp(colorImage[a], x, y).alpha;
  878. int32_t heightPixel = (image_readPixel_clamp(depthBuffer, x, y) - minBound.y) * heightScale;
  879. image_writePixel(heightImage[a], x, y, ColorRgbaI32(heightPixel, 0, 0, opacityPixel));
  880. }
  881. }
  882. }
  883. // Crop all images uniformly for easy atlas packing
  884. int32_t minX = width;
  885. int32_t minY = height;
  886. int32_t maxX = 0;
  887. int32_t maxY = 0;
  888. for (int a = 0; a < cameraAngles; a++) {
  889. for (int y = 0; y < height; y++) {
  890. for (int x = 0; x < width; x++) {
  891. if (image_readPixel_border(colorImage[a], x, y).alpha) {
  892. if (x < minX) minX = x;
  893. if (x > maxX) maxX = x;
  894. if (y < minY) minY = y;
  895. if (y > maxY) maxY = y;
  896. }
  897. }
  898. }
  899. }
  900. // Check if cropping failed
  901. if (minX > maxX) {
  902. printText(" There's nothing visible in the model, because cropping the final images returned nothing!\n");
  903. return;
  904. }
  905. IRect cropRegion = IRect(minX, minY, (maxX + 1) - minX, (maxY + 1) - minY);
  906. if (cropRegion.width() < 1 || cropRegion.height() < 1) {
  907. printText(" Cropping failed to find any drawn pixels!\n");
  908. return;
  909. }
  910. for (int a = 0; a < cameraAngles; a++) {
  911. colorImage[a] = image_getSubImage(colorImage[a], cropRegion);
  912. heightImage[a] = image_getSubImage(heightImage[a], cropRegion);
  913. normalImage[a] = image_getSubImage(normalImage[a], cropRegion);
  914. }
  915. int croppedWidth = cropRegion.width();
  916. int croppedHeight = cropRegion.height();
  917. int centerX = width / 2 - cropRegion.left();
  918. int centerY = height / 2 - cropRegion.top();
  919. printText(" Cropped images of ", croppedWidth, "x", croppedHeight, " pixels with centers at (", centerX, ", ", centerY, ")\n");
  920. // Pack everything into an image atlas
  921. targetAtlas = image_create_RgbaU8(croppedWidth * 3, croppedHeight * cameraAngles);
  922. for (int a = 0; a < cameraAngles; a++) {
  923. draw_copy(targetAtlas, colorImage[a], 0, a * croppedHeight);
  924. draw_copy(targetAtlas, heightImage[a], croppedWidth, a * croppedHeight);
  925. draw_copy(targetAtlas, normalImage[a], croppedWidth * 2, a * croppedHeight);
  926. }
  927. SpriteConfig config = SpriteConfig(centerX, centerY, cameraAngles, 3, minBound, maxBound);
  928. if (model_exists(shadowModel) && model_getNumberOfPoints(shadowModel) > 0) {
  929. config.appendShadow(shadowModel);
  930. }
  931. targetConfigText = config.toIni();
  932. }
  933. }
  934. // Allowing the last decimals to deviate a bit because floating-point operations are rounded differently between computers
  935. static bool approximateTextMatch(const ReadableString &a, const ReadableString &b, double tolerance = 0.00002) {
  936. int readerA = 0, readerB = 0;
  937. while (readerA < string_length(a) && readerB < string_length(b)) {
  938. DsrChar charA = a[readerA];
  939. DsrChar charB = b[readerB];
  940. if (character_isValueCharacter(charA) && character_isValueCharacter(charB)) {
  941. // Scan forward on both sides while consuming content and comparing the actual value
  942. int startA = readerA;
  943. int startB = readerB;
  944. // Only move forward on valid characters
  945. if (a[readerA] == U'-') { readerA++; }
  946. if (b[readerB] == U'-') { readerB++; }
  947. while (character_isDigit(a[readerA])) { readerA++; }
  948. while (character_isDigit(b[readerB])) { readerB++; }
  949. if (a[readerA] == U'.') { readerA++; }
  950. if (b[readerB] == U'.') { readerB++; }
  951. while (character_isDigit(a[readerA])) { readerA++; }
  952. while (character_isDigit(b[readerB])) { readerB++; }
  953. // Approximate values
  954. double valueA = string_toDouble(string_exclusiveRange(a, startA, readerA));
  955. double valueB = string_toDouble(string_exclusiveRange(b, startB, readerB));
  956. // Check the difference
  957. double diff = valueB - valueA;
  958. if (diff > tolerance || diff < -tolerance) {
  959. // Too big difference, this is probably not a rounding error
  960. return false;
  961. }
  962. } else if (charA != charB) {
  963. // Difference with a non-value involved
  964. return false;
  965. }
  966. readerA++;
  967. readerB++;
  968. }
  969. if (readerA < string_length(a) - 1 || readerB < string_length(b) - 1) {
  970. // One text had unmatched remains after the other reached its end
  971. return false;
  972. } else {
  973. return true;
  974. }
  975. }
  976. void sprite_generateFromModel(const Model& visibleModel, const Model& shadowModel, const OrthoSystem& ortho, const String& targetPath, int cameraAngles, bool debug) {
  977. // Generate an image and a configuration file from the visible model
  978. ImageRgbaU8 atlasImage; String configText;
  979. sprite_generateFromModel(atlasImage, configText, visibleModel, shadowModel, ortho, targetPath, cameraAngles);
  980. // Save the result on success
  981. if (string_length(configText) > 0) {
  982. // Save the atlas
  983. String atlasPath = targetPath + U".png";
  984. // Try loading any existing image
  985. ImageRgbaU8 existingAtlasImage = image_load_RgbaU8(atlasPath, false);
  986. if (image_exists(existingAtlasImage)) {
  987. int difference = image_maxDifference(atlasImage, existingAtlasImage);
  988. if (difference <= 2) {
  989. printText(" No significant changes against ", targetPath, ".\n");
  990. } else {
  991. image_save(atlasImage, atlasPath);
  992. printText(" Updated ", targetPath, " with a deviation of ", difference, ".\n");
  993. }
  994. } else {
  995. // Only save if there was no existing image or it differed significantly from the new result
  996. // This comparison is made to avoid flooding version history with changes from invisible differences in color rounding
  997. image_save(atlasImage, atlasPath);
  998. printText(" Saved atlas to ", targetPath, ".\n");
  999. }
  1000. // Save the configuration
  1001. String configPath = targetPath + U".ini";
  1002. String oldConfixText = string_load(configPath, false);
  1003. if (approximateTextMatch(configText, oldConfixText)) {
  1004. printText(" No significant changes against ", targetPath, ".\n\n");
  1005. } else {
  1006. string_save(targetPath + U".ini", configText);
  1007. printText(" Saved sprite config to ", targetPath, ".\n\n");
  1008. }
  1009. if (debug) {
  1010. ImageRgbaU8 debugImage; String garbageText;
  1011. // TODO: Show overlap between visible and shadow so that shadow outside of visible is displayed as bright red on a dark model.
  1012. // The number of visible shadow pixels should be reported automatically
  1013. // in an error message at the end of the total execution together with file names.
  1014. sprite_generateFromModel(debugImage, garbageText, shadowModel, Model(), ortho, targetPath + U"Debug", 8);
  1015. image_save(debugImage, targetPath + U"Debug.png");
  1016. }
  1017. }
  1018. }
  1019. }