tool.cpp 23 KB

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