tool.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. TODO:
  3. * Make alternative models for animated characters and damaged buildings.
  4. * Make the custom rendering system able to render directly into a game with triangle culling and clipping.
  5. */
  6. #include <assert.h>
  7. #include <limits>
  8. #include <functional>
  9. #include "../../DFPSR/includeFramework.h"
  10. #include "sprite/spriteAPI.h"
  11. using namespace dsr;
  12. static constexpr float colorScale = 1.0f / 255.0f;
  13. static FVector4D pixelToVertexColor(const ColorRgbaI32& color) {
  14. return FVector4D(color.red * colorScale, color.green * colorScale, color.blue * colorScale, 1.0f);
  15. }
  16. static int createTriangle(Model& model, int part, int indexA, int indexB, int indexC, FVector4D colorA, FVector4D colorB, FVector4D colorC, bool flip = false) {
  17. if (flip) {
  18. int poly = model_addTriangle(model, part, indexB, indexA, indexC);
  19. model_setVertexColor(model, part, poly, 0, colorB);
  20. model_setVertexColor(model, part, poly, 1, colorA);
  21. model_setVertexColor(model, part, poly, 2, colorC);
  22. return poly;
  23. } else {
  24. int poly = model_addTriangle(model, part, indexA, indexB, indexC);
  25. model_setVertexColor(model, part, poly, 0, colorA);
  26. model_setVertexColor(model, part, poly, 1, colorB);
  27. model_setVertexColor(model, part, poly, 2, colorC);
  28. return poly;
  29. }
  30. }
  31. using TransformFunction = std::function<FVector3D(int pixelX, int pixelY, int displacement)>;
  32. // Returns the start point index for another side to weld against
  33. int createGridSide(Model& model, int part, const ImageU8& heightMap, const ImageRgbaU8& colorMap,
  34. const TransformFunction& transform, bool clipZero, bool mergeSides, bool flipDepth = false, bool flipFaces = false, int otherStartPointIndex = -1) {
  35. int startPointIndex = model_getNumberOfPoints(model);
  36. int mapWidth = image_getWidth(heightMap);
  37. int mapHeight = image_getHeight(heightMap);
  38. int flipScale = flipDepth ? -1 : 1;
  39. int columns = mergeSides ? mapWidth + 1 : mapWidth;
  40. // Create a part for the polygons
  41. for (int z = 0; z < mapHeight; z++) {
  42. for (int x = 0; x < columns; x++) {
  43. // Sample the height map and convert to world space
  44. int cx = x % mapWidth;
  45. int heightC = image_readPixel_border(heightMap, cx, z);
  46. // Add the point to the model
  47. if (x < mapWidth) {
  48. // Create a position from the 3D index
  49. model_addPoint(model, transform(x, z, heightC * flipScale));
  50. }
  51. if (x > 0 && z > 0) {
  52. // Create vertex data
  53. // A-B
  54. // |
  55. // D-C
  56. int px = x - 1;
  57. int cz = z;
  58. int pz = z - 1;
  59. // Sample previous heights
  60. int heightA = image_readPixel_border(heightMap, px, pz);
  61. int heightB = image_readPixel_border(heightMap, cx, pz);
  62. int heightD = image_readPixel_border(heightMap, px, cz);
  63. // Tell where to weld with another side's points
  64. bool weldA = otherStartPointIndex > -1 && heightA == 0;
  65. bool weldB = otherStartPointIndex > -1 && heightB == 0;
  66. bool weldC = otherStartPointIndex > -1 && heightC == 0;
  67. bool weldD = otherStartPointIndex > -1 && heightD == 0;
  68. // Get indices to points
  69. int indexA = (weldA ? otherStartPointIndex : startPointIndex) + px + pz * mapWidth;
  70. int indexB = (weldB ? otherStartPointIndex : startPointIndex) + cx + pz * mapWidth;
  71. int indexC = (weldC ? otherStartPointIndex : startPointIndex) + cx + cz * mapWidth;
  72. int indexD = (weldD ? otherStartPointIndex : startPointIndex) + px + cz * mapWidth;
  73. // Sample colors
  74. FVector4D colorA = pixelToVertexColor(image_readPixel_tile(colorMap, px, pz));
  75. FVector4D colorB = pixelToVertexColor(image_readPixel_tile(colorMap, cx, pz));
  76. FVector4D colorC = pixelToVertexColor(image_readPixel_tile(colorMap, cx, cz));
  77. FVector4D colorD = pixelToVertexColor(image_readPixel_tile(colorMap, px, cz));
  78. // Decide how to split triangles and which ones to display
  79. bool acSplit = false;
  80. bool skipFirst = false;
  81. bool skipSecond = false;
  82. if (heightA == 0 && heightC == 0) {
  83. // ABCD fan of ABC and ACD
  84. acSplit = true;
  85. if (heightB == 0) { skipFirst = true; }
  86. if (heightD == 0) { skipSecond = true; }
  87. } else if (heightB == 0 && heightD == 0) {
  88. // BCDA fan of ACD and BDA
  89. acSplit = false;
  90. if (heightC == 0) { skipFirst = true; }
  91. if (heightA == 0) { skipSecond = true; }
  92. } else {
  93. int cA = image_readPixel_tile(heightMap, cx - 2, cz - 2);
  94. int cB = image_readPixel_tile(heightMap, cx + 1, cz - 2);
  95. int cC = image_readPixel_tile(heightMap, cx + 1, cz + 1);
  96. int cD = image_readPixel_tile(heightMap, cx - 2, cz + 1);
  97. int diffAC = abs((cA + cC) - (heightA + heightC));
  98. int diffBD = abs((cB + cD) - (heightB + heightD));
  99. acSplit = diffBD > diffAC;
  100. }
  101. if (!clipZero) {
  102. skipFirst = false;
  103. skipSecond = false;
  104. }
  105. // Create a polygon
  106. if (!(skipFirst && skipSecond)) {
  107. if (acSplit) {
  108. if (!skipFirst) {
  109. createTriangle(model, part,
  110. indexA, indexB, indexC,
  111. colorA, colorB, colorC, flipFaces
  112. );
  113. }
  114. if (!skipSecond) {
  115. createTriangle(model, part,
  116. indexA, indexC, indexD,
  117. colorA, colorC, colorD, flipFaces
  118. );
  119. }
  120. } else {
  121. if (!skipFirst) {
  122. createTriangle(model, part,
  123. indexB, indexC, indexD,
  124. colorB, colorC, colorD, flipFaces
  125. );
  126. }
  127. if (!skipSecond) {
  128. createTriangle(model, part,
  129. indexB, indexD, indexA,
  130. colorB, colorD, colorA, flipFaces
  131. );
  132. }
  133. }
  134. }
  135. }
  136. }
  137. }
  138. return startPointIndex;
  139. }
  140. // clipZero:
  141. // Removing triangles from pixels with displacement zero.
  142. // Used for carving out non-square shapes using black height as the background.
  143. // mergeSides:
  144. // Connect vertices from the left side of the image with the right side using additional polygons.
  145. // Used for cylinder shapes to remove the seam where the sides meet.
  146. // mirror:
  147. // Create another instance of the height field with surfaces and displacement turned in the other direction.
  148. // weldNormals:
  149. // Merges normals between mirrored sides to let normals at displacement zero merge with the other side.
  150. // mirror must be active for this to have an effect, because there's no mirrored side to weld against otherwise.
  151. // clipZero must be active to hide polygons without a normal. (What is the average direction of two opposing planes?)
  152. void createGrid(Model& model, int part, const ImageU8& heightMap, const ImageRgbaU8& colorMap,
  153. const TransformFunction& transform, bool clipZero, bool mergeSides, bool mirror, bool weldNormals) {
  154. if (weldNormals && !mirror) {
  155. printText("\n Warning! Cannot weld normals without a mirrored side. The \"weldNormals\" will be ignored because \"mirror\" was not active.\n\n");
  156. weldNormals = false;
  157. }
  158. if (weldNormals && !clipZero) {
  159. printText("\n Warning! Cannot weld normals without clipping zero displacement. The \"weldNormals\" will be ignored because \"clipZero\" was not active.\n\n");
  160. weldNormals = false;
  161. }
  162. // Generate primary side
  163. int otherStartPointIndex = createGridSide(model, part, heightMap, colorMap, transform, clipZero, mergeSides);
  164. // Generate additional mirrored side
  165. if (mirror) {
  166. createGridSide(model, part, heightMap, colorMap, transform, clipZero, mergeSides, true, true, weldNormals ? otherStartPointIndex : -1);
  167. }
  168. }
  169. // The part of ParserState that resets when creating a new part but is kept after generating geometry
  170. struct PartSettings {
  171. Transform3D location;
  172. float displacement = 1.0f, patchWidth = 1.0f, patchHeight = 1.0f, radius = 0.0f;
  173. int clipZero = 0; // 1 will cut away displacements from height zero, 0 will try to display all polygons
  174. int mirror = 0; // 1 will let height fields generate polygons on both sides to create solid shapes
  175. PartSettings() {}
  176. };
  177. struct ParserState {
  178. String sourcePath;
  179. int angles = 4;
  180. Model model, shadow;
  181. int part = -1; // Current part index for model (No index used for shadows)
  182. PartSettings partSettings;
  183. explicit ParserState(const String& sourcePath) : sourcePath(sourcePath), model(model_create()), shadow(model_create()) {
  184. model_addEmptyPart(this->shadow, U"shadow");
  185. }
  186. };
  187. static void parse_scope(ParserState& state, const ReadableString& key) {
  188. // End the previous scope
  189. state.partSettings = PartSettings();
  190. state.part = -1;
  191. if (string_caseInsensitiveMatch(key, U"PART")) {
  192. // Enter a new part's scope
  193. printText(" New part begins\n");
  194. state.part = model_addEmptyPart(state.model, U"part");
  195. } else {
  196. printText(" Unrecognized scope ", key, " within <>.\n");
  197. }
  198. }
  199. #define MATCH_ASSIGN_GLOBAL(NAME,ACCESS,PARSER,DESCRIPTION) \
  200. if (string_caseInsensitiveMatch(key, NAME)) { \
  201. ACCESS = PARSER(value); \
  202. printText(" ", #DESCRIPTION, " = ", ACCESS, "\n"); \
  203. }
  204. #define MATCH_ASSIGN(BLOCK,NAME,ACCESS,PARSER,DESCRIPTION) \
  205. if (string_caseInsensitiveMatch(key, NAME)) { \
  206. if (state.BLOCK == -1) { \
  207. printText(" Cannot assign ", DESCRIPTION, " without a ", #BLOCK, ".\n"); \
  208. } else { \
  209. ACCESS = PARSER(value); \
  210. printText(" ", #DESCRIPTION, " = ", ACCESS, "\n"); \
  211. } \
  212. }
  213. static void parse_assignment(ParserState& state, const ReadableString& key, const ReadableString& value) {
  214. MATCH_ASSIGN_GLOBAL(U"Angles", state.angles, string_parseInteger, "camera angle count")
  215. else MATCH_ASSIGN(part, U"Origin", state.partSettings.location.position, parseFVector3D, "origin")
  216. else MATCH_ASSIGN(part, U"XAxis", state.partSettings.location.transform.xAxis, parseFVector3D, "X-Axis")
  217. else MATCH_ASSIGN(part, U"YAxis", state.partSettings.location.transform.yAxis, parseFVector3D, "Y-Axis")
  218. else MATCH_ASSIGN(part, U"ZAxis", state.partSettings.location.transform.zAxis, parseFVector3D, "Z-Axis")
  219. else MATCH_ASSIGN(part, U"Displacement", state.partSettings.displacement, string_parseDouble, "displacement")
  220. else MATCH_ASSIGN(part, U"ClipZero", state.partSettings.clipZero, string_parseInteger, "zero clipping")
  221. else MATCH_ASSIGN(part, U"Mirror", state.partSettings.mirror, string_parseInteger, "mirror flag")
  222. else MATCH_ASSIGN(part, U"PatchWidth", state.partSettings.patchWidth, string_parseDouble, "patch width")
  223. else MATCH_ASSIGN(part, U"PatchHeight", state.partSettings.patchHeight, string_parseDouble, "patch height")
  224. else MATCH_ASSIGN(part, U"Radius", state.partSettings.radius, string_parseDouble, "radius")
  225. else {
  226. printText(" Tried to assign ", value, " to unrecognized key ", key, ".\n");
  227. }
  228. }
  229. enum class Shape {
  230. None, Plane, Box, Cylinder
  231. };
  232. static Shape ShapeFromName(const ReadableString& name) {
  233. if (string_caseInsensitiveMatch(name, U"PLANE")) {
  234. return Shape::Plane;
  235. } else if (string_caseInsensitiveMatch(name, U"BOX")) {
  236. return Shape::Box;
  237. } else if (string_caseInsensitiveMatch(name, U"CYLINDER")) {
  238. return Shape::Cylinder;
  239. } else {
  240. throwError("Unhandled shape \"", name, "\"!\n");
  241. return Shape::None;
  242. }
  243. }
  244. static String nameOfShape(Shape shape) {
  245. if (shape == Shape::None) {
  246. return U"None";
  247. } else if (shape == Shape::Plane) {
  248. return U"Plane";
  249. } else if (shape == Shape::Box) {
  250. return U"Box";
  251. } else if (shape == Shape::Cylinder) {
  252. return U"Cylinder";
  253. } else {
  254. return U"?";
  255. }
  256. }
  257. // TODO: Arguments for repeating the input images so that pillars can reuse textures for multiple sides when only one camera angle will be saved
  258. static void generateField(ParserState& state, Shape shape, const ImageU8& heightMap, const ImageRgbaU8& colorMap, bool shadow) {
  259. Transform3D system = state.partSettings.location;
  260. bool clipZero = state.partSettings.clipZero;
  261. float offsetPerUnit = state.partSettings.displacement / 255.0f;
  262. bool mirror = state.partSettings.mirror != 0;
  263. bool mergeSides = shape == Shape::Cylinder;
  264. bool weldNormals = mirror && clipZero;
  265. // Create a transform function based on the shape
  266. TransformFunction transform;
  267. if (shape == Shape::Plane) {
  268. // PatchWidth along local X
  269. // PatchHeight along local Z
  270. // Displacement along local Y
  271. float widthScale = state.partSettings.patchWidth / (image_getWidth(heightMap) - 1);
  272. float heightScale = state.partSettings.patchHeight / -(image_getHeight(heightMap) - 1);
  273. FVector3D localScaling = FVector3D(widthScale, offsetPerUnit, heightScale);
  274. FVector3D localOrigin = FVector3D(state.partSettings.patchWidth * -0.5f, 0.0f, state.partSettings.patchHeight * 0.5f);
  275. transform = [system, localOrigin, localScaling](int pixelX, int pixelY, int displacement){
  276. return system.transformPoint(localOrigin + (FVector3D(pixelX, displacement, pixelY) * localScaling));
  277. };
  278. } else if (shape == Shape::Cylinder) {
  279. // Radius + Displacement along local X, Z
  280. // PatchHeight along local Y
  281. float radius = state.partSettings.radius;
  282. float angleScale = 6.283185307f / image_getWidth(heightMap);
  283. float angleOffset = angleScale * 0.5f; // Start and end half a pixel from the seam
  284. float heightScale = state.partSettings.patchHeight / -(image_getHeight(heightMap) - 1);
  285. float heightOffset = state.partSettings.patchHeight * 0.5f;
  286. int lastRow = image_getHeight(heightMap) - 1;
  287. bool fillHoles = !mirror && !clipZero; // Automatically fill the holes to close the shape when not mirroring nor clipping the sides
  288. transform = [system, angleOffset, angleScale, heightOffset, heightScale, radius, offsetPerUnit, fillHoles, lastRow](int pixelX, int pixelY, int displacement){
  289. float angle = ((float)pixelX * angleScale) + angleOffset;
  290. float offset = ((float)displacement * offsetPerUnit) + radius;
  291. float height = ((float)pixelY * heightScale) + heightOffset;
  292. if (fillHoles && (pixelY == 0 || pixelY == lastRow)) {
  293. offset = 0.0f;
  294. }
  295. return system.transformPoint(FVector3D(-sin(angle) * offset, height, cos(angle) * offset));
  296. };
  297. } else {
  298. printText("Field generation is not implemented for ", nameOfShape(shape), "!\n");
  299. return;
  300. }
  301. if (shadow) {
  302. createGrid(state.shadow, 0, heightMap, colorMap, transform, clipZero, mergeSides, mirror, weldNormals);
  303. } else {
  304. createGrid(state.model, state.part, heightMap, colorMap, transform, clipZero, mergeSides, mirror, weldNormals);
  305. }
  306. }
  307. static void generateBasicShape(ParserState& state, Shape shape, const ReadableString& arg1, const ReadableString& arg2, const ReadableString& arg3, bool shadow) {
  308. Transform3D system = state.partSettings.location;
  309. Model model = shadow ? state.shadow : state.model;
  310. int part = shadow ? 0 : state.part;
  311. // All shapes are centered around the axis system's origin from -0.5 to +0.5 of any given size
  312. if (shape == Shape::Box) {
  313. // Parse arguments
  314. float width = string_parseDouble(arg1);
  315. float height = string_parseDouble(arg2);
  316. float depth = string_parseDouble(arg3);
  317. // Create a bound
  318. FVector3D upper = FVector3D(width, height, depth) * 0.5f;
  319. FVector3D lower = -upper;
  320. // Positions
  321. int first = model_getNumberOfPoints(model);
  322. model_addPoint(model, system.transformPoint(FVector3D(lower.x, lower.y, lower.z))); // first + 0: Left-down-near
  323. model_addPoint(model, system.transformPoint(FVector3D(lower.x, lower.y, upper.z))); // first + 1: Left-down-far
  324. model_addPoint(model, system.transformPoint(FVector3D(lower.x, upper.y, lower.z))); // first + 2: Left-up-near
  325. model_addPoint(model, system.transformPoint(FVector3D(lower.x, upper.y, upper.z))); // first + 3: Left-up-far
  326. model_addPoint(model, system.transformPoint(FVector3D(upper.x, lower.y, lower.z))); // first + 4: Right-down-near
  327. model_addPoint(model, system.transformPoint(FVector3D(upper.x, lower.y, upper.z))); // first + 5: Right-down-far
  328. model_addPoint(model, system.transformPoint(FVector3D(upper.x, upper.y, lower.z))); // first + 6: Right-up-near
  329. model_addPoint(model, system.transformPoint(FVector3D(upper.x, upper.y, upper.z))); // first + 7: Right-up-far
  330. // Polygons
  331. model_addQuad(model, part, first + 3, first + 2, first + 0, first + 1); // Left quad
  332. model_addQuad(model, part, first + 6, first + 7, first + 5, first + 4); // Right quad
  333. model_addQuad(model, part, first + 2, first + 6, first + 4, first + 0); // Front quad
  334. model_addQuad(model, part, first + 7, first + 3, first + 1, first + 5); // Back quad
  335. model_addQuad(model, part, first + 3, first + 7, first + 6, first + 2); // Top quad
  336. model_addQuad(model, part, first + 0, first + 4, first + 5, first + 1); // Bottom quad
  337. } else if (shape == Shape::Cylinder) {
  338. // Parse arguments
  339. float radius = string_parseDouble(arg1);
  340. float height = string_parseDouble(arg2);
  341. int sideCount = string_parseDouble(arg3);
  342. // Create a bound
  343. float topHeight = height * 0.5f;
  344. float bottomHeight = height * -0.5f;
  345. // Positions
  346. float angleScale = 6.283185307 / (float)sideCount;
  347. int centerTop = model_addPoint(model, system.transformPoint(FVector3D(0.0f, topHeight, 0.0f)));
  348. int firstTopSide = model_getNumberOfPoints(model);
  349. for (int p = 0; p < sideCount; p++) {
  350. float radians = p * angleScale;
  351. model_addPoint(model, system.transformPoint(FVector3D(sin(radians) * radius, topHeight, cos(radians) * radius)));
  352. }
  353. int centerBottom = model_addPoint(model, system.transformPoint(FVector3D(0.0f, bottomHeight, 0.0f)));
  354. int firstBottomSide = model_getNumberOfPoints(model);
  355. for (int p = 0; p < sideCount; p++) {
  356. float radians = p * angleScale;
  357. model_addPoint(model, system.transformPoint(FVector3D(sin(radians) * radius, bottomHeight, cos(radians) * radius)));
  358. }
  359. for (int p = 0; p < sideCount; p++) {
  360. int q = (p + 1) % sideCount;
  361. // Top fan
  362. model_addTriangle(model, part, centerTop, firstTopSide + p, firstTopSide + q);
  363. // Bottom fan
  364. model_addTriangle(model, part, centerBottom, firstBottomSide + q, firstBottomSide + p);
  365. // Side
  366. model_addQuad(model, part, firstTopSide + q, firstTopSide + p, firstBottomSide + p, firstBottomSide + q);
  367. }
  368. } else {
  369. printText("Basic shape generation is not implemented for ", nameOfShape(shape), "!\n");
  370. return;
  371. }
  372. }
  373. // Used when displaying shadow models for debugging
  374. static ImageRgbaU8 createDebugTexture() {
  375. ImageRgbaU8 result = image_create_RgbaU8(2, 2);
  376. image_writePixel(result, 0, 0, ColorRgbaI32(255, 0, 0, 255));
  377. image_writePixel(result, 1, 0, ColorRgbaI32(0, 255, 0, 255));
  378. image_writePixel(result, 0, 1, ColorRgbaI32(0, 0, 255, 255));
  379. image_writePixel(result, 1, 1, ColorRgbaI32(255, 255, 0, 255));
  380. return result;
  381. }
  382. ImageRgbaU8 debugTexture = createDebugTexture();
  383. static void parse_shape(ParserState& state, List<ReadableString>& args, bool shadow) {
  384. if (state.part == -1) {
  385. printText(" Cannot generate a ", args[0], " without a part.\n");
  386. }
  387. Shape shape = ShapeFromName(args[0]);
  388. if (args.length() == 2) {
  389. // Shape, HeightMap
  390. ImageU8 heightMap = image_get_red(image_load_RgbaU8(state.sourcePath + args[1]));
  391. generateField(state, shape, heightMap, debugTexture, shadow);
  392. } else if (args.length() == 3) {
  393. // Shape, HeightMap, ColorMap
  394. ImageU8 heightMap = image_get_red(image_load_RgbaU8(state.sourcePath + args[1]));
  395. ImageRgbaU8 colorMap = image_load_RgbaU8(state.sourcePath + args[2]);
  396. generateField(state, shape, heightMap, colorMap, shadow);
  397. } else if (args.length() == 4) {
  398. // Shape, Width, Height, Depth
  399. generateBasicShape(state, shape, args[1], args[2], args[3], shadow);
  400. } else {
  401. printText(" The ", args[0], " shape needs at least a height map to know the number of vertices to generate. A color map can also be given.\n");
  402. }
  403. }
  404. static void parse_command(ParserState& state, const ReadableString& command, const ReadableString& argContent) {
  405. List<ReadableString> args = argContent.split(U',');
  406. for (int a = 0; a < args.length(); a++) {
  407. args[a] = string_removeOuterWhiteSpace(args[a]);
  408. }
  409. if (string_caseInsensitiveMatch(command, U"Visible")) {
  410. parse_shape(state, args, false);
  411. } else if (string_caseInsensitiveMatch(command, U"Shadow")) {
  412. parse_shape(state, args, true);
  413. } else {
  414. printText(" Unrecognized command ", command, ".\n");
  415. }
  416. }
  417. static void parse_dsm(ParserState& state, const ReadableString& content) {
  418. List<ReadableString> lines = content.split(U'\n');
  419. for (int l = 0; l < lines.length(); l++) {
  420. // Get the current line
  421. ReadableString line = lines[l];
  422. // Skip comments
  423. int commentIndex = line.findFirst(U';');
  424. if (commentIndex > -1) {
  425. line = line.before(commentIndex);
  426. }
  427. // Find assignments
  428. int assignmentIndex = line.findFirst(U'=');
  429. int colonIndex = line.findFirst(U':');
  430. int blockStartIndex = line.findFirst(U'<');
  431. int blockEndIndex = line.findFirst(U'>');
  432. if (assignmentIndex > -1) {
  433. ReadableString key = string_removeOuterWhiteSpace(line.before(assignmentIndex));
  434. ReadableString value = string_removeOuterWhiteSpace(line.after(assignmentIndex));
  435. parse_assignment(state, key, value);
  436. } else if (colonIndex > -1) {
  437. ReadableString command = string_removeOuterWhiteSpace(line.before(colonIndex));
  438. ReadableString argContent = line.after(colonIndex);
  439. parse_command(state, command, argContent);
  440. } else if (blockStartIndex > -1 && blockEndIndex > -1) {
  441. String block = string_removeOuterWhiteSpace(line.inclusiveRange(blockStartIndex + 1, blockEndIndex - 1));
  442. parse_scope(state, block);
  443. } else if (line.length() > 0) {
  444. printText("Unrecognized line \"", line, "\".\n");
  445. }
  446. }
  447. }
  448. void processScript(const String& sourcePath, const String& targetPath, OrthoSystem ortho, const String& scriptName) {
  449. // Initialize a parser state containing an empty model
  450. ParserState state = ParserState(sourcePath);
  451. // Parse the script to fill the state with a model and additional render settings
  452. String scriptPath = string_combine(state.sourcePath, scriptName, U".dsm");
  453. printText("Generating ", scriptPath, "\n");
  454. parse_dsm(state, string_load(scriptPath));
  455. // Render the model
  456. sprite_generateFromModel(state.model, state.shadow, ortho, targetPath + scriptName, state.angles, true);
  457. }
  458. // The first argument is the source folder in which the model scripts are stored.
  459. // The second argument is the target folder in which the results are saved.
  460. // The third argument is the ortho configuration file path.
  461. // The following arguments are plain names of the scripts to process without any path nor extension.
  462. void tool_main(int argn, char **argv) {
  463. if (argn < 5) {
  464. printText("Nothing to process. Terminating sprite generation tool.\n");
  465. } else {
  466. String sourcePath = string_combine(argv[1], file_separator());
  467. String targetPath = string_combine(argv[2], file_separator());
  468. OrthoSystem ortho = OrthoSystem(string_load(String(argv[3])));
  469. for (int a = 4; a < argn; a++) {
  470. processScript(sourcePath, targetPath, ortho, String(argv[a]));
  471. }
  472. }
  473. }