obj.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package obj is used to parse the Wavefront OBJ file format (*.obj), including
  5. // associated materials (*.mtl). Not all features of the OBJ format are
  6. // supported. Basic format info: https://en.wikipedia.org/wiki/Wavefront_.obj_file
  7. package obj
  8. import (
  9. "bufio"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "math"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "github.com/g3n/engine/core"
  19. "github.com/g3n/engine/geometry"
  20. "github.com/g3n/engine/gls"
  21. "github.com/g3n/engine/graphic"
  22. "github.com/g3n/engine/material"
  23. "github.com/g3n/engine/math32"
  24. "github.com/g3n/engine/texture"
  25. )
  26. // Decoder contains all decoded data from the obj and mtl files
  27. type Decoder struct {
  28. Objects []Object // decoded objects
  29. Matlib string // name of the material lib
  30. Materials map[string]*Material // maps material name to object
  31. Vertices math32.ArrayF32 // vertices positions array
  32. Normals math32.ArrayF32 // vertices normals
  33. Uvs math32.ArrayF32 // vertices texture coordinates
  34. Warnings []string // warning messages
  35. line uint // current line number
  36. objCurrent *Object // current object
  37. matCurrent *Material // current material
  38. smoothCurrent bool // current smooth state
  39. mtlDir string // Directory of material file
  40. }
  41. // Object contains all information about one decoded object
  42. type Object struct {
  43. Name string // Object name
  44. Faces []Face // Faces
  45. materials []string // Materials used in this object
  46. }
  47. // Face contains all information about an object face
  48. type Face struct {
  49. Vertices []int // Indices to the face vertices
  50. Uvs []int // Indices to the face UV coordinates
  51. Normals []int // Indices to the face normals
  52. Material string // Material name
  53. Smooth bool // Smooth face
  54. }
  55. // Material contains all information about an object material
  56. type Material struct {
  57. Name string // Material name
  58. Illum int // Illumination model
  59. Opacity float32 // Opacity factor
  60. Refraction float32 // Refraction factor
  61. Shininess float32 // Shininess (specular exponent)
  62. Ambient math32.Color // Ambient color reflectivity
  63. Diffuse math32.Color // Diffuse color reflectivity
  64. Specular math32.Color // Specular color reflectivity
  65. Emissive math32.Color // Emissive color
  66. MapKd string // Texture file linked to diffuse color
  67. }
  68. // Light gray default material used as when other materials cannot be loaded.
  69. var defaultMat = &Material{
  70. Diffuse: math32.Color{R: 0.7, G: 0.7, B: 0.7},
  71. Ambient: math32.Color{R: 0.7, G: 0.7, B: 0.7},
  72. Specular: math32.Color{R: 0.5, G: 0.5, B: 0.5},
  73. Shininess: 30.0,
  74. }
  75. // Local constants
  76. const (
  77. blanks = "\r\n\t "
  78. invINDEX = math.MaxUint32
  79. objType = "obj"
  80. mtlType = "mtl"
  81. )
  82. // Decode decodes the specified obj and mtl files returning a decoder
  83. // object and an error. Passing an empty string (or otherwise invalid path)
  84. // to mtlpath will cause the decoder to check the 'mtllib' file in the OBJ if
  85. // present, and fall back to a default material as a last resort.
  86. func Decode(objpath string, mtlpath string) (*Decoder, error) {
  87. // Opens obj file
  88. fobj, err := os.Open(objpath)
  89. if err != nil {
  90. return nil, err
  91. }
  92. defer fobj.Close()
  93. // Opens mtl file
  94. // if mtlpath=="", then os.Open() will produce an error,
  95. // causing fmtl to be nil
  96. fmtl, err := os.Open(mtlpath)
  97. defer fmtl.Close() // will produce (ignored) err if fmtl==nil
  98. // if fmtl==nil, the io.Reader in DecodeReader() will be (T=*os.File, V=nil)
  99. // which is NOT equal to plain nil or (io.Reader, nil) but will produce
  100. // the desired result of passing nil to DecodeReader() per it's func comment.
  101. dec, err := DecodeReader(fobj, fmtl)
  102. if err != nil {
  103. return nil, err
  104. }
  105. dec.mtlDir = filepath.Dir(objpath)
  106. return dec, nil
  107. }
  108. // DecodeReader decodes the specified obj and mtl readers returning a decoder
  109. // object and an error if a problem was encoutered while parsing the OBJ.
  110. //
  111. // Pass a valid io.Reader to override the materials defined in the OBJ file,
  112. // or `nil` to use the materials listed in the OBJ's "mtllib" line (if present),
  113. // a ".mtl" file with the same name as the OBJ file if presemt, or a default
  114. // material as a last resort. No error will be returned for problems
  115. // with materials--a gray default material will be used if nothing else works.
  116. func DecodeReader(objreader, mtlreader io.Reader) (*Decoder, error) {
  117. dec := new(Decoder)
  118. dec.Objects = make([]Object, 0)
  119. dec.Warnings = make([]string, 0)
  120. dec.Materials = make(map[string]*Material)
  121. dec.Vertices = math32.NewArrayF32(0, 0)
  122. dec.Normals = math32.NewArrayF32(0, 0)
  123. dec.Uvs = math32.NewArrayF32(0, 0)
  124. dec.line = 1
  125. // Parses obj lines
  126. err := dec.parse(objreader, dec.parseObjLine)
  127. if err != nil {
  128. return nil, err
  129. }
  130. // Parses mtl lines
  131. // 1) try passed in mtlreader,
  132. // 2) try file in mtllib line
  133. // 3) try <obj_filename>.mtl
  134. // 4) use default material as last resort
  135. dec.matCurrent = nil
  136. dec.line = 1
  137. // first try: use the material file passed in as an io.Reader
  138. err = dec.parse(mtlreader, dec.parseMtlLine)
  139. if err != nil {
  140. // 2) if mtlreader produces an error (eg. it's nil), try the file listed
  141. // in the OBJ's matlib line, if it exists.
  142. if dec.Matlib != "" {
  143. // ... first need to get the path of the OBJ, since mtllib is relative
  144. var mtllibPath string
  145. if objf, ok := objreader.(*os.File); ok {
  146. // NOTE (quillaja): this is a hack because we need the directory of
  147. // the OBJ, but can't get it any other way (dec.mtlDir isn't set
  148. // until AFTER this function is finished).
  149. objdir := filepath.Dir(objf.Name())
  150. mtllibPath = filepath.Join(objdir, dec.Matlib)
  151. dec.mtlDir = objdir // NOTE (quillaja): should this be set?
  152. }
  153. mtlf, errMTL := os.Open(mtllibPath)
  154. defer mtlf.Close()
  155. if errMTL == nil {
  156. err = dec.parse(mtlf, dec.parseMtlLine) // will set err to nil if successful
  157. }
  158. }
  159. // 3) if the mtllib line fails try <obj_filename>.mtl in the same directory.
  160. // process is basically identical to the above code block.
  161. if err != nil {
  162. var mtlpath string
  163. if objf, ok := objreader.(*os.File); ok {
  164. objdir := strings.TrimSuffix(objf.Name(), ".obj")
  165. mtlpath = objdir + ".mtl"
  166. dec.mtlDir = objdir // NOTE (quillaja): should this be set?
  167. }
  168. mtlf, errMTL := os.Open(mtlpath)
  169. defer mtlf.Close()
  170. if errMTL == nil {
  171. err = dec.parse(mtlf, dec.parseMtlLine) // will set err to nil if successful
  172. if err == nil {
  173. // log a warning
  174. msg := fmt.Sprintf("using material file %s", mtlpath)
  175. dec.appendWarn(mtlType, msg)
  176. }
  177. }
  178. }
  179. // 4) handle error(s) instead of simply passing it up the call stack.
  180. // range over the materials named in the OBJ file and substitute a default
  181. // But log that an error occured.
  182. if err != nil {
  183. for key := range dec.Materials {
  184. dec.Materials[key] = defaultMat
  185. }
  186. // NOTE (quillaja): could be an error of some custom type. But people
  187. // tend to ignore errors and pass them up the call stack instead
  188. // of handling them... so all this work would probably be wasted.
  189. dec.appendWarn(mtlType, "unable to parse a material file for obj. using default material instead.")
  190. }
  191. }
  192. return dec, nil
  193. }
  194. // NewGroup creates and returns a group containing as children meshes
  195. // with all the decoded objects.
  196. // A group is returned even if there is only one object decoded.
  197. func (dec *Decoder) NewGroup() (*core.Node, error) {
  198. group := core.NewNode()
  199. for i := 0; i < len(dec.Objects); i++ {
  200. mesh, err := dec.NewMesh(&dec.Objects[i])
  201. if err != nil {
  202. return nil, err
  203. }
  204. group.Add(mesh)
  205. }
  206. return group, nil
  207. }
  208. // NewMesh creates and returns a mesh from an specified decoded object.
  209. func (dec *Decoder) NewMesh(obj *Object) (*graphic.Mesh, error) {
  210. // Creates object geometry
  211. geom, err := dec.NewGeometry(obj)
  212. if err != nil {
  213. return nil, err
  214. }
  215. // Single material
  216. if geom.GroupCount() == 1 {
  217. // get Material info from mtl file and ensure it's valid.
  218. // substitute default material if it is not.
  219. var matDesc *Material
  220. var matName string
  221. if len(obj.materials) > 0 {
  222. matName = obj.materials[0]
  223. }
  224. matDesc = dec.Materials[matName]
  225. if matDesc == nil {
  226. matDesc = defaultMat
  227. // log warning
  228. msg := fmt.Sprintf("could not find material for %s. using default material.", obj.Name)
  229. dec.appendWarn(objType, msg)
  230. }
  231. // Creates material for mesh
  232. mat := material.NewPhong(&matDesc.Diffuse)
  233. ambientColor := mat.AmbientColor()
  234. mat.SetAmbientColor(ambientColor.Multiply(&matDesc.Ambient))
  235. mat.SetSpecularColor(&matDesc.Specular)
  236. mat.SetShininess(matDesc.Shininess)
  237. // Loads material textures if specified
  238. err = dec.loadTex(&mat.Material, matDesc)
  239. if err != nil {
  240. return nil, err
  241. }
  242. return graphic.NewMesh(geom, mat), nil
  243. }
  244. // Multi material
  245. mesh := graphic.NewMesh(geom, nil)
  246. for idx := 0; idx < geom.GroupCount(); idx++ {
  247. group := geom.GroupAt(idx)
  248. // get Material info from mtl file and ensure it's valid.
  249. // substitute default material if it is not.
  250. var matDesc *Material
  251. var matName string
  252. if len(obj.materials) > group.Matindex {
  253. matName = obj.materials[group.Matindex]
  254. }
  255. matDesc = dec.Materials[matName]
  256. if matDesc == nil {
  257. matDesc = defaultMat
  258. // log warning
  259. msg := fmt.Sprintf("could not find material for %s. using default material.", obj.Name)
  260. dec.appendWarn(objType, msg)
  261. }
  262. // Creates material for mesh
  263. matGroup := material.NewPhong(&matDesc.Diffuse)
  264. ambientColor := matGroup.AmbientColor()
  265. matGroup.SetAmbientColor(ambientColor.Multiply(&matDesc.Ambient))
  266. matGroup.SetSpecularColor(&matDesc.Specular)
  267. matGroup.SetShininess(matDesc.Shininess)
  268. // Loads material textures if specified
  269. err = dec.loadTex(&matGroup.Material, matDesc)
  270. if err != nil {
  271. return nil, err
  272. }
  273. mesh.AddGroupMaterial(matGroup, idx)
  274. }
  275. return mesh, nil
  276. }
  277. // NewGeometry generates and returns a geometry from the specified object
  278. func (dec *Decoder) NewGeometry(obj *Object) (*geometry.Geometry, error) {
  279. geom := geometry.NewGeometry()
  280. // Create buffers
  281. positions := math32.NewArrayF32(0, 0)
  282. normals := math32.NewArrayF32(0, 0)
  283. uvs := math32.NewArrayF32(0, 0)
  284. indices := math32.NewArrayU32(0, 0)
  285. // copy all vertex info from the decoded Object, face and index to the geometry
  286. copyVertex := func(face *Face, idx int) {
  287. var vec3 math32.Vector3
  288. var vec2 math32.Vector2
  289. pos := positions.Size() / 3
  290. // Copy vertex position and append to geometry
  291. dec.Vertices.GetVector3(3*face.Vertices[idx], &vec3)
  292. positions.AppendVector3(&vec3)
  293. // Copy vertex normal and append to geometry
  294. if face.Normals[idx] != invINDEX {
  295. dec.Normals.GetVector3(3*face.Normals[idx], &vec3)
  296. normals.AppendVector3(&vec3)
  297. }
  298. // Copy vertex uv and append to geometry
  299. if face.Uvs[idx] != invINDEX {
  300. dec.Uvs.GetVector2(2*face.Uvs[idx], &vec2)
  301. uvs.AppendVector2(&vec2)
  302. }
  303. indices.Append(uint32(pos))
  304. }
  305. var group *geometry.Group
  306. matName := ""
  307. matIndex := 0
  308. for _, face := range obj.Faces {
  309. // If face material changed, starts a new group
  310. if face.Material != matName {
  311. group = geom.AddGroup(indices.Size(), 0, matIndex)
  312. matName = face.Material
  313. matIndex++
  314. }
  315. // Copy face vertices to geometry
  316. for idx := 1; idx < len(face.Vertices)-1; idx++ {
  317. copyVertex(&face, 0)
  318. copyVertex(&face, idx)
  319. copyVertex(&face, idx+1)
  320. group.Count += 3
  321. }
  322. }
  323. geom.SetIndices(indices)
  324. geom.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))
  325. geom.AddVBO(gls.NewVBO(normals).AddAttrib(gls.VertexNormal))
  326. geom.AddVBO(gls.NewVBO(uvs).AddAttrib(gls.VertexTexcoord))
  327. return geom, nil
  328. }
  329. // loadTex loads textures described in the material descriptor into the
  330. // specified material
  331. func (dec *Decoder) loadTex(mat *material.Material, desc *Material) error {
  332. // Checks if material descriptor specified texture
  333. if desc.MapKd == "" {
  334. return nil
  335. }
  336. // Get texture file path
  337. // If texture file path is not absolute assumes it is relative
  338. // to the directory of the material file
  339. var texPath string
  340. if filepath.IsAbs(desc.MapKd) {
  341. texPath = desc.MapKd
  342. } else {
  343. texPath = filepath.Join(dec.mtlDir, desc.MapKd)
  344. }
  345. // Try to load texture from image file
  346. tex, err := texture.NewTexture2DFromImage(texPath)
  347. if err != nil {
  348. return err
  349. }
  350. mat.AddTexture(tex)
  351. return nil
  352. }
  353. // parse reads the lines from the specified reader and dispatch them
  354. // to the specified line parser.
  355. func (dec *Decoder) parse(reader io.Reader, parseLine func(string) error) error {
  356. bufin := bufio.NewReader(reader)
  357. dec.line = 1
  358. for {
  359. // Reads next line and abort on errors (not EOF)
  360. line, err := bufin.ReadString('\n')
  361. if err != nil && err != io.EOF {
  362. return err
  363. }
  364. // Parses the line
  365. line = strings.Trim(line, blanks)
  366. perr := parseLine(line)
  367. if perr != nil {
  368. return perr
  369. }
  370. // If EOF ends of parsing.
  371. if err == io.EOF {
  372. break
  373. }
  374. dec.line++
  375. }
  376. return nil
  377. }
  378. // Parses obj file line, dispatching to specific parsers
  379. func (dec *Decoder) parseObjLine(line string) error {
  380. // Ignore empty lines
  381. fields := strings.Fields(line)
  382. if len(fields) == 0 {
  383. return nil
  384. }
  385. // Ignore comment lines
  386. ltype := fields[0]
  387. if strings.HasPrefix(ltype, "#") {
  388. return nil
  389. }
  390. switch ltype {
  391. // Material library
  392. case "mtllib":
  393. return dec.parseMatlib(fields[1:])
  394. // Object name
  395. case "o":
  396. return dec.parseObject(fields[1:])
  397. // Group names. We are considering "group" the same as "object"
  398. // This may not be right
  399. case "g":
  400. return dec.parseObject(fields[1:])
  401. // Vertex coordinate
  402. case "v":
  403. return dec.parseVertex(fields[1:])
  404. // Vertex normal coordinate
  405. case "vn":
  406. return dec.parseNormal(fields[1:])
  407. // Vertex texture coordinate
  408. case "vt":
  409. return dec.parseTex(fields[1:])
  410. // Face vertex
  411. case "f":
  412. return dec.parseFace(fields[1:])
  413. // Use material
  414. case "usemtl":
  415. return dec.parseUsemtl(fields[1:])
  416. // Smooth
  417. case "s":
  418. return dec.parseSmooth(fields[1:])
  419. default:
  420. dec.appendWarn(objType, "field not supported: "+ltype)
  421. }
  422. return nil
  423. }
  424. // Parses a mtllib line:
  425. // mtllib <name>
  426. func (dec *Decoder) parseMatlib(fields []string) error {
  427. if len(fields) < 1 {
  428. return errors.New("Material library (mtllib) with no fields")
  429. }
  430. dec.Matlib = fields[0]
  431. return nil
  432. }
  433. // Parses an object line:
  434. // o <name>
  435. func (dec *Decoder) parseObject(fields []string) error {
  436. if len(fields) < 1 {
  437. return errors.New("Object line (o) with no fields")
  438. }
  439. var ob Object
  440. ob.Name = fields[0]
  441. ob.Faces = make([]Face, 0)
  442. ob.materials = make([]string, 0)
  443. dec.Objects = append(dec.Objects, ob)
  444. dec.objCurrent = &dec.Objects[len(dec.Objects)-1]
  445. return nil
  446. }
  447. // Parses a vertex position line
  448. // v <x> <y> <z> [w]
  449. func (dec *Decoder) parseVertex(fields []string) error {
  450. if len(fields) < 3 {
  451. return errors.New("Less than 3 vertices in 'v' line")
  452. }
  453. for _, f := range fields[:3] {
  454. val, err := strconv.ParseFloat(f, 32)
  455. if err != nil {
  456. return err
  457. }
  458. dec.Vertices.Append(float32(val))
  459. }
  460. return nil
  461. }
  462. // Parses a vertex normal line
  463. // vn <x> <y> <z>
  464. func (dec *Decoder) parseNormal(fields []string) error {
  465. if len(fields) < 3 {
  466. return errors.New("Less than 3 normals in 'vn' line")
  467. }
  468. for _, f := range fields[:3] {
  469. val, err := strconv.ParseFloat(f, 32)
  470. if err != nil {
  471. return err
  472. }
  473. dec.Normals.Append(float32(val))
  474. }
  475. return nil
  476. }
  477. // Parses a vertex texture coordinate line:
  478. // vt <u> <v> <w>
  479. func (dec *Decoder) parseTex(fields []string) error {
  480. if len(fields) < 2 {
  481. return errors.New("Less than 2 texture coords. in 'vt' line")
  482. }
  483. for _, f := range fields[:2] {
  484. val, err := strconv.ParseFloat(f, 32)
  485. if err != nil {
  486. return err
  487. }
  488. dec.Uvs.Append(float32(val))
  489. }
  490. return nil
  491. }
  492. // parseFace parses a face decription line:
  493. // f v1[/vt1][/vn1] v2[/vt2][/vn2] v3[/vt3][/vn3] ...
  494. func (dec *Decoder) parseFace(fields []string) error {
  495. // If current object has no material, appends last material if defined
  496. if len(dec.objCurrent.materials) == 0 && dec.matCurrent != nil {
  497. dec.objCurrent.materials = append(dec.objCurrent.materials, dec.matCurrent.Name)
  498. }
  499. if len(fields) < 3 {
  500. return dec.formatError("Face line with less 3 fields")
  501. }
  502. var face Face
  503. face.Vertices = make([]int, len(fields))
  504. face.Uvs = make([]int, len(fields))
  505. face.Normals = make([]int, len(fields))
  506. if dec.matCurrent != nil {
  507. face.Material = dec.matCurrent.Name
  508. } else {
  509. // TODO (quillaja): do something better than spamming warnings for each line
  510. // dec.appendWarn(objType, "No material defined")
  511. face.Material = "internal default" // causes error on in NewGeom() if ""
  512. // dec.matCurrent = defaultMat
  513. }
  514. face.Smooth = dec.smoothCurrent
  515. for pos, f := range fields {
  516. // Separate the current field in its components: v vt vn
  517. vfields := strings.Split(f, "/")
  518. if len(vfields) < 1 {
  519. return dec.formatError("Face field with no parts")
  520. }
  521. // Get the index of this vertex position (must always exist)
  522. val, err := strconv.ParseInt(vfields[0], 10, 32)
  523. if err != nil {
  524. return err
  525. }
  526. // Positive index is an absolute vertex index
  527. if val > 0 {
  528. face.Vertices[pos] = int(val - 1)
  529. // Negative vertex index is relative to the last parsed vertex
  530. } else if val < 0 {
  531. current := (len(dec.Vertices) / 3) - 1
  532. face.Vertices[pos] = current + int(val) + 1
  533. // Vertex index could never be 0
  534. } else {
  535. return dec.formatError("Face vertex index value equal to 0")
  536. }
  537. // Get the index of this vertex UV coordinate (optional)
  538. if len(vfields) > 1 && len(vfields[1]) > 0 {
  539. val, err := strconv.ParseInt(vfields[1], 10, 32)
  540. if err != nil {
  541. return err
  542. }
  543. // Positive index is an absolute UV index
  544. if val > 0 {
  545. face.Uvs[pos] = int(val - 1)
  546. // Negative vertex index is relative to the last parsed uv
  547. } else if val < 0 {
  548. current := (len(dec.Uvs) / 2) - 1
  549. face.Uvs[pos] = current + int(val) + 1
  550. // UV index could never be 0
  551. } else {
  552. return dec.formatError("Face uv index value equal to 0")
  553. }
  554. } else {
  555. face.Uvs[pos] = invINDEX
  556. }
  557. // Get the index of this vertex normal (optional)
  558. if len(vfields) >= 3 {
  559. val, err = strconv.ParseInt(vfields[2], 10, 32)
  560. if err != nil {
  561. return err
  562. }
  563. // Positive index is an absolute normal index
  564. if val > 0 {
  565. face.Normals[pos] = int(val - 1)
  566. // Negative vertex index is relative to the last parsed normal
  567. } else if val < 0 {
  568. current := (len(dec.Normals) / 3) - 1
  569. face.Normals[pos] = current + int(val) + 1
  570. // Normal index could never be 0
  571. } else {
  572. return dec.formatError("Face normal index value equal to 0")
  573. }
  574. } else {
  575. face.Normals[pos] = invINDEX
  576. }
  577. }
  578. // Appends this face to the current object
  579. dec.objCurrent.Faces = append(dec.objCurrent.Faces, face)
  580. return nil
  581. }
  582. // parseUsemtl parses a "usemtl" decription line:
  583. // usemtl <name>
  584. func (dec *Decoder) parseUsemtl(fields []string) error {
  585. if len(fields) < 1 {
  586. return dec.formatError("Usemtl with no fields")
  587. }
  588. // Checks if this material has already been parsed
  589. name := fields[0]
  590. mat := dec.Materials[name]
  591. // Creates material descriptor
  592. if mat == nil {
  593. mat = new(Material)
  594. mat.Name = name
  595. dec.Materials[name] = mat
  596. }
  597. dec.objCurrent.materials = append(dec.objCurrent.materials, name)
  598. // Set this as the current material
  599. dec.matCurrent = mat
  600. return nil
  601. }
  602. // parseSmooth parses a "s" decription line:
  603. // s <0|1>
  604. func (dec *Decoder) parseSmooth(fields []string) error {
  605. if len(fields) < 1 {
  606. return dec.formatError("'s' with no fields")
  607. }
  608. if fields[0] == "0" || fields[0] == "off" {
  609. dec.smoothCurrent = false
  610. return nil
  611. }
  612. if fields[0] == "1" || fields[0] == "on" {
  613. dec.smoothCurrent = true
  614. return nil
  615. }
  616. return dec.formatError("'s' with invalid value")
  617. }
  618. /******************************************************************************
  619. mtl parse functions
  620. */
  621. // Parses material file line, dispatching to specific parsers
  622. func (dec *Decoder) parseMtlLine(line string) error {
  623. // Ignore empty lines
  624. fields := strings.Fields(line)
  625. if len(fields) == 0 {
  626. return nil
  627. }
  628. // Ignore comment lines
  629. ltype := fields[0]
  630. if strings.HasPrefix(ltype, "#") {
  631. return nil
  632. }
  633. switch ltype {
  634. case "newmtl":
  635. return dec.parseNewmtl(fields[1:])
  636. case "d":
  637. return dec.parseDissolve(fields[1:])
  638. case "Ka":
  639. return dec.parseKa(fields[1:])
  640. case "Kd":
  641. return dec.parseKd(fields[1:])
  642. case "Ke":
  643. return dec.parseKe(fields[1:])
  644. case "Ks":
  645. return dec.parseKs(fields[1:])
  646. case "Ni":
  647. return dec.parseNi(fields[1:])
  648. case "Ns":
  649. return dec.parseNs(fields[1:])
  650. case "illum":
  651. return dec.parseIllum(fields[1:])
  652. case "map_Kd":
  653. return dec.parseMapKd(fields[1:])
  654. default:
  655. dec.appendWarn(mtlType, "field not supported: "+ltype)
  656. }
  657. return nil
  658. }
  659. // Parses new material definition
  660. // newmtl <mat_name>
  661. func (dec *Decoder) parseNewmtl(fields []string) error {
  662. if len(fields) < 1 {
  663. return dec.formatError("newmtl with no fields")
  664. }
  665. // Checks if material has already been seen
  666. name := fields[0]
  667. mat := dec.Materials[name]
  668. // Creates material descriptor
  669. if mat == nil {
  670. mat = new(Material)
  671. mat.Name = name
  672. dec.Materials[name] = mat
  673. }
  674. dec.matCurrent = mat
  675. return nil
  676. }
  677. // Parses the dissolve factor (opacity)
  678. // d <factor>
  679. func (dec *Decoder) parseDissolve(fields []string) error {
  680. if len(fields) < 1 {
  681. return dec.formatError("'d' with no fields")
  682. }
  683. val, err := strconv.ParseFloat(fields[0], 32)
  684. if err != nil {
  685. return dec.formatError("'d' parse float error")
  686. }
  687. dec.matCurrent.Opacity = float32(val)
  688. return nil
  689. }
  690. // Parses ambient reflectivity:
  691. // Ka r g b
  692. func (dec *Decoder) parseKa(fields []string) error {
  693. if len(fields) < 3 {
  694. return dec.formatError("'Ka' with less than 3 fields")
  695. }
  696. var colors [3]float32
  697. for pos, f := range fields[:3] {
  698. val, err := strconv.ParseFloat(f, 32)
  699. if err != nil {
  700. return err
  701. }
  702. colors[pos] = float32(val)
  703. }
  704. dec.matCurrent.Ambient.Set(colors[0], colors[1], colors[2])
  705. return nil
  706. }
  707. // Parses diffuse reflectivity:
  708. // Kd r g b
  709. func (dec *Decoder) parseKd(fields []string) error {
  710. if len(fields) < 3 {
  711. return dec.formatError("'Kd' with less than 3 fields")
  712. }
  713. var colors [3]float32
  714. for pos, f := range fields[:3] {
  715. val, err := strconv.ParseFloat(f, 32)
  716. if err != nil {
  717. return err
  718. }
  719. colors[pos] = float32(val)
  720. }
  721. dec.matCurrent.Diffuse.Set(colors[0], colors[1], colors[2])
  722. return nil
  723. }
  724. // Parses emissive color:
  725. // Ke r g b
  726. func (dec *Decoder) parseKe(fields []string) error {
  727. if len(fields) < 3 {
  728. return dec.formatError("'Ke' with less than 3 fields")
  729. }
  730. var colors [3]float32
  731. for pos, f := range fields[:3] {
  732. val, err := strconv.ParseFloat(f, 32)
  733. if err != nil {
  734. return err
  735. }
  736. colors[pos] = float32(val)
  737. }
  738. dec.matCurrent.Emissive.Set(colors[0], colors[1], colors[2])
  739. return nil
  740. }
  741. // Parses specular reflectivity:
  742. // Ks r g b
  743. func (dec *Decoder) parseKs(fields []string) error {
  744. if len(fields) < 3 {
  745. return dec.formatError("'Ks' with less than 3 fields")
  746. }
  747. var colors [3]float32
  748. for pos, f := range fields[:3] {
  749. val, err := strconv.ParseFloat(f, 32)
  750. if err != nil {
  751. return err
  752. }
  753. colors[pos] = float32(val)
  754. }
  755. dec.matCurrent.Specular.Set(colors[0], colors[1], colors[2])
  756. return nil
  757. }
  758. // Parses optical density, also known as index of refraction
  759. // Ni <optical_density>
  760. func (dec *Decoder) parseNi(fields []string) error {
  761. if len(fields) < 1 {
  762. return dec.formatError("'Ni' with no fields")
  763. }
  764. val, err := strconv.ParseFloat(fields[0], 32)
  765. if err != nil {
  766. return dec.formatError("'d' parse float error")
  767. }
  768. dec.matCurrent.Refraction = float32(val)
  769. return nil
  770. }
  771. // Parses specular exponent
  772. // Ns <specular_exponent>
  773. func (dec *Decoder) parseNs(fields []string) error {
  774. if len(fields) < 1 {
  775. return dec.formatError("'Ns' with no fields")
  776. }
  777. val, err := strconv.ParseFloat(fields[0], 32)
  778. if err != nil {
  779. return dec.formatError("'d' parse float error")
  780. }
  781. dec.matCurrent.Shininess = float32(val)
  782. return nil
  783. }
  784. // Parses illumination model (0 to 10)
  785. // illum <ilum_#>
  786. func (dec *Decoder) parseIllum(fields []string) error {
  787. if len(fields) < 1 {
  788. return dec.formatError("'illum' with no fields")
  789. }
  790. val, err := strconv.ParseUint(fields[0], 10, 32)
  791. if err != nil {
  792. return dec.formatError("'d' parse int error")
  793. }
  794. dec.matCurrent.Illum = int(val)
  795. return nil
  796. }
  797. // Parses color texture linked to the diffuse reflectivity of the material
  798. // map_Kd [-options] <filename>
  799. func (dec *Decoder) parseMapKd(fields []string) error {
  800. if len(fields) < 1 {
  801. return dec.formatError("No fields")
  802. }
  803. dec.matCurrent.MapKd = fields[0]
  804. return nil
  805. }
  806. func (dec *Decoder) formatError(msg string) error {
  807. return fmt.Errorf("%s in line:%d", msg, dec.line)
  808. }
  809. func (dec *Decoder) appendWarn(ftype string, msg string) {
  810. wline := fmt.Sprintf("%s(%d): %s", ftype, dec.line, msg)
  811. dec.Warnings = append(dec.Warnings, wline)
  812. }