summaryrefslogtreecommitdiff
path: root/tools/ase/main.c
blob: 6ba770ace1f27f36c6c16712cb033c34c48072df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#include <model.h>

#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Lexeme {
  const char* str;
  size_t      length;
} Lexeme;

typedef struct Lexer {
  const char* buffer; // Input buffer.
  size_t      size;   // Buffer size.
  size_t      next;   // Points to the next, unconsumed character.
  Lexeme      lexeme; // Current lexeme.
} Lexer;

static void LexerMake(const char* data, size_t size, Lexer* lexer) {
  assert(data);
  assert(lexer);
  lexer->buffer = data;
  lexer->size   = size;
}

static bool End(const Lexer* lexer) {
  assert(lexer);
  assert(lexer->next <= lexer->size);
  return lexer->next == lexer->size;
}

static bool HasNext(const Lexer* lexer) {
  assert(lexer);
  return lexer->next < lexer->size;
}

static void Advance(Lexer* lexer) {
  assert(lexer);
  assert(HasNext(lexer));
  lexer->next++;
}

static char Next(const Lexer* lexer) {
  assert(lexer);
  assert(HasNext(lexer));
  return lexer->buffer[lexer->next];
}

static const char* NextPtr(const Lexer* lexer) {
  assert(lexer);
  assert(HasNext(lexer));
  return &lexer->buffer[lexer->next];
}

// Get the pointer to the next character, or one past the last character of the
// buffer (the "end" of the buffer).
static const char* NextOrEndPtr(const Lexer* lexer) {
  assert(lexer);
  assert(HasNext(lexer) || End(lexer));
  return &lexer->buffer[lexer->next];
}

static void SkipChar(Lexer* lexer) {
  assert(lexer);
  if (HasNext(lexer)) {
    Advance(lexer);
  }
}

static void SkipLine(Lexer* lexer) {
  assert(lexer);
  // Advance until we find a newline character.
  while (HasNext(lexer) &&
         (Next(lexer) != '\n')) Advance(lexer);
  // Skip the newline character.
  SkipChar(lexer);
}

static bool IsWhiteSpace(char c) {
  return (c == ' ') || (c == '\n');
}

static void SkipWhiteSpace(Lexer* lexer) {
  assert(lexer);
  while (HasNext(lexer) &&
         IsWhiteSpace(Next(lexer))) Advance(lexer);
}

static void ReadUntilWhiteSpace(Lexer* lexer) {
  assert(lexer);
  while (HasNext(lexer) &&
         !IsWhiteSpace(Next(lexer))) Advance(lexer);
}

static bool NextLexeme(Lexer* lexer) {
  assert(lexer);
  SkipWhiteSpace(lexer);
  if (HasNext(lexer)) {
    lexer->lexeme.str = NextPtr(lexer);
    ReadUntilWhiteSpace(lexer); // Find the end of the lexeme.
    lexer->lexeme.length = NextOrEndPtr(lexer) - lexer->lexeme.str;
  } else {
    lexer->lexeme.str    = nullptr;
    lexer->lexeme.length = 0;
  }
  return lexer->lexeme.length > 0;
}

static bool ParseFloat(const Lexeme* lex, float* out) {
  assert(lex);
  assert(out);
  assert(errno == 0);
  *out = (float)strtod(lex->str, nullptr);
  return errno == 0;
}

static inline bool IsLexeme(const Lexer* lexer, const char* expected) {
  assert(lexer);
  assert(expected);
  return strncmp(lexer->lexeme.str, expected, lexer->lexeme.length) == 0;
}

// Reasonable limits for the parser implementation.
// The model spec does not impose a limit on tris, but vertex attributes are
// indexed by uint16_t.
#define MAX_TRIS  65536
#define MAX_VERTS 65536

// Temporary storage for model data. A Model can be outputted from this.
typedef struct ModelData {
  uint32_t numTris;
  uint32_t numPositions;
  uint32_t numNormals;
  uint32_t numTexcoords;
  mdTri    tris     [MAX_TRIS];
  mdVec3   positions[MAX_VERTS];
  mdVec3   normals  [MAX_VERTS];
  mdVec2   texcoords[MAX_VERTS];
} ModelData;

static bool ParseObj(Lexer* lexer, ModelData* modelData) {
  assert(lexer);
  assert(modelData);
  #define PRINT(STR)      printf("%s%.*s\n", STR, (int)lexer->lexeme.length, lexer->lexeme.str)
  #define LEX(STR)        IsLexeme(lexer, STR)
  #define NEXT_LEXEME()   { if (!NextLexeme(lexer)) break; else PRINT("~ "); }
  #define NEXT_FLOAT(PTR) { NEXT_LEXEME(); if (!ParseFloat(&lexer->lexeme, PTR)) break; }
  bool consumeNext = true;
  for (;;) {
    if (consumeNext) {
      NEXT_LEXEME();
    }
    consumeNext = true;
    if (LEX("#")) {
      SkipLine(lexer);
    } else if (LEX("mtllib")) {
      NEXT_LEXEME(); // material file
      PRINT("> material: ");
    } else if (LEX("o")) {
      NEXT_LEXEME(); // object name
      PRINT("> object: ");
    } else if (LEX("v")) {
      float x, y, z;
      NEXT_FLOAT(&x);
      NEXT_FLOAT(&y);
      NEXT_FLOAT(&z);
      modelData->positions[modelData->numPositions++] = (mdVec3){x, y, z};
      printf("> position: %.2f, %.2f, %.2f\n", x, y, z);
    } else if (LEX("vn")) {
      float x, y, z;
      NEXT_FLOAT(&x);
      NEXT_FLOAT(&y);
      NEXT_FLOAT(&z);
      modelData->normals[modelData->numNormals++] = (mdVec3){x, y, z};
      printf("> normal: %.2f, %.2f, %.2f\n", x, y, z);
    } else if (LEX("vt")) {
      float s, t;
      NEXT_FLOAT(&s);
      NEXT_FLOAT(&t);
      modelData->texcoords[modelData->numTexcoords++] = (mdVec2){s, t};
      printf("> texcoord: %.2f, %.2f\n", s, t);
    } else if (LEX("f")) {
      // Indices are 1-based.
      // Texcoord and normal are optional.
      mdVert vertices[4]; // Handling up to quads.
      int numVerts = 0;
      while (NextLexeme(lexer)) {
        int pos, tex, normal;
        if (sscanf(lexer->lexeme.str, "%d/%d/%d", &pos, &tex, &normal) == 3) {
          vertices[numVerts++] = (mdVert){pos-1, tex-1, normal-1};
          printf("> vertex: %d/%d/%d\n", pos, tex, normal);
        } else if (sscanf(lexer->lexeme.str, "%d//%d", &pos, &normal) == 2) {
          vertices[numVerts++] = (mdVert){pos-1, -1, normal-1};
          printf("> vertex: %d//%d\n", pos, normal);
        } else if (sscanf(lexer->lexeme.str, "%d/%d", &pos, &tex) == 2) {
          vertices[numVerts++] = (mdVert){pos-1, tex-1, -1};
          printf("> vertex: %d/%d\n", pos, tex);
        } else if (sscanf(lexer->lexeme.str, "%d", &pos) == 1) {
          vertices[numVerts++] = (mdVert){pos-1, -1, -1};
          printf("> vertex: %d\n", pos);
        } else { // Something past the face.
          consumeNext = false;
          break;
        }
      }
      // End of vertices for this face; output the model triangles.
      assert((numVerts == 3) || (numVerts == 4));
      if (numVerts == 3) {
        modelData->tris[modelData->numTris++] =
          (mdTri){vertices[0], vertices[1], vertices[2]};
      } else if (numVerts == 4) {
        // Triangulate the quad and output two triangles instead.
        modelData->tris[modelData->numTris++] =
          (mdTri){vertices[0], vertices[1], vertices[2]};
        modelData->tris[modelData->numTris++] =
          (mdTri){vertices[0], vertices[2], vertices[3]};
      }
    }
  }
  return true;
}

static bool WriteModelFile(const ModelData* modelData, const char* path) {
  assert(modelData);
  assert(path);
  
  bool success = false;
  FILE* file   = nullptr;
  Model model  = {0};
  
  // Fill the Model header.
  IndexedModel* indexed    = &model.indexed;
  model.type               = ModelTypeIndexed;
  indexed->numTris         = modelData->numTris;
  indexed->numPositions    = modelData->numPositions;
  indexed->numNormals      = modelData->numNormals;
  indexed->numTexcoords    = modelData->numTexcoords;
  indexed->offsetTris      = 0; // 'data' member.
  indexed->offsetPositions = indexed->offsetTris      + (modelData->numTris      * sizeof(mdTri));
  indexed->offsetNormals   = indexed->offsetPositions + (modelData->numPositions * sizeof(mdVec3));
  indexed->offsetTexcoords = indexed->offsetNormals   + (modelData->numNormals   * sizeof(mdVec3));
  
  if ((file = fopen(path, "wb")) == nullptr) {
    fprintf(stderr, "Failed opening output file for writing: %s\n", path);
    goto cleanup;
  }
  // Header.
  if (fwrite(&model, sizeof(model), 1, file) != 1) {
    fprintf(stderr, "Failed writing Model header\n");
    goto cleanup;
  }
  // Tris.
  if (fwrite(&modelData->tris, sizeof(mdTri), modelData->numTris, file) != modelData->numTris) {
    fprintf(stderr, "Failed writing triangles\n");
    goto cleanup;
  }
  // Positions.
  if (fwrite(&modelData->positions, sizeof(mdVec3), modelData->numPositions, file) != modelData->numPositions) {
    fprintf(stderr, "Failed writing positions\n");
    goto cleanup;
  }
  // Normals.
  if (fwrite(&modelData->normals, sizeof(mdVec3), modelData->numNormals, file) != modelData->numNormals) {
    fprintf(stderr, "Failed writing normals\n");
    goto cleanup;
  }
  // Texcoords.
  if (fwrite(&modelData->texcoords, sizeof(mdVec2), modelData->numTexcoords, file) != modelData->numTexcoords) {
    fprintf(stderr, "Failed writing texture coordinates\n");goto cleanup;
  }
  
  success = true;

cleanup:
  if (file) {
    fclose(file);
  }
  return success;
}

static bool ReadFile(const char* path, uint8_t** outData, size_t* outSize) {
  assert(path);

  bool     success = false;
  uint8_t* data    = nullptr;
  FILE*    file    = nullptr;
  
  if ((file = fopen(path, "rb")) == nullptr) {
    goto cleanup;
  }
  if (fseek(file, 0, SEEK_END) != 0) {
    goto cleanup;
  }
  const size_t fileSize = ftell(file);
  if (fileSize == (size_t)(-1)) {
    goto cleanup;
  }
  // Allocate one extra byte so that text file data conveniently ends with null.
  const size_t size = fileSize + 1;
  if (fseek(file, 0, SEEK_SET) != 0) {
    goto cleanup;
  }
  if ((data = calloc(1, size)) == nullptr) {
    goto cleanup;
  }
  if (fread(data, fileSize, 1, file) != 1) {
    goto cleanup;
  }
  
  *outData = data;
  *outSize = size;
  success = true;
  
cleanup:
  if (file) {
    fclose(file);
  }
  if (!success && (data != nullptr)) {
    free(data);
  }
  return success;
}

static void usage(const char* argv0) {
  fprintf(stderr, "Usage: %s <model file> [out.mdl]\n", argv0);
  fprintf(stderr, "\n");
  fprintf(stderr, "Supported file formats:\n");
  fprintf(stderr, "  OBJ\n");
}

int main(int argc, const char** argv) {
  if ((argc != 2) && (argc != 3)) {
    usage(argv[0]);
    return 1;
  }
  
  const char* filePath = argv[1];
  const char* outPath  = (argc > 2) ? argv[2] : "out.mdl";
  
  bool       success   = false;
  uint8_t*   fileData  = nullptr;
  size_t     dataSize  = 0;
  ModelData* modelData = nullptr;
  Lexer      lexer     = {0};
  
  // TODO: Map file to memory instead?
  if (!ReadFile(filePath, &fileData, &dataSize)) {
    goto cleanup;
  }
  if ((modelData = calloc(1, sizeof(ModelData))) == nullptr) {
    goto cleanup;
  }
  LexerMake((const char*)fileData, dataSize, &lexer);
  
  if (!ParseObj(&lexer, modelData)) {
    goto cleanup;
  }
  if (!WriteModelFile(modelData, outPath)) {
    goto cleanup;
  }
  
  success = true;
  
cleanup:
  if (modelData) {
    free(modelData);
  }
  if (fileData) {
    free(fileData);
  }
  return success ? 0 : 1;
}