obj.go 20 KB

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