obj.go 20 KB

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