spriteAPI.cpp 57 KB

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