obj.go 22 KB

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