spriteAPI.cpp 67 KB

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