common.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 collada
  5. import (
  6. "bytes"
  7. "encoding/xml"
  8. "fmt"
  9. "io"
  10. "strconv"
  11. "strings"
  12. )
  13. //
  14. // Source
  15. //
  16. type Source struct {
  17. Id string // Source id
  18. Name string // Source name
  19. ArrayElement interface{} // Array element (FloatArray|others)
  20. TechniqueCommon struct {
  21. Accessor Accessor
  22. }
  23. }
  24. // Dump prints out information about the Source
  25. func (s *Source) Dump(out io.Writer, indent int) {
  26. fmt.Fprintf(out, "%sSource id:%s name:%s\n", sIndent(indent), s.Id, s.Name)
  27. ind := indent + step
  28. switch at := s.ArrayElement.(type) {
  29. case *FloatArray:
  30. at.Dump(out, ind)
  31. case *NameArray:
  32. at.Dump(out, ind)
  33. }
  34. fmt.Fprintf(out, "%sTechniqueCommon\n", sIndent(ind))
  35. s.TechniqueCommon.Accessor.Dump(out, ind+3)
  36. }
  37. //
  38. // NameArray
  39. //
  40. type NameArray struct {
  41. Id string
  42. Name string
  43. Count int
  44. Data []string
  45. }
  46. // Dump prints out information about the NameArray
  47. func (na *NameArray) Dump(out io.Writer, indent int) {
  48. fmt.Fprintf(out, "%sNameArray id:%s count:%d\n", sIndent(indent), na.Id, na.Count)
  49. ind := indent + step
  50. fmt.Fprintf(out, "%sData(%d):%s\n", sIndent(ind), len(na.Data), na.Data)
  51. }
  52. //
  53. // FloatArray
  54. //
  55. type FloatArray struct {
  56. Id string
  57. Count int
  58. Data []float32
  59. }
  60. // Dump prints out information about the FloatArray
  61. func (fa *FloatArray) Dump(out io.Writer, indent int) {
  62. fmt.Fprintf(out, "%sFloatArray id:%s count:%d\n", sIndent(indent), fa.Id, fa.Count)
  63. ind := indent + step
  64. fmt.Fprintf(out, "%sData(%d):%s\n", sIndent(ind), len(fa.Data), f32sToString(fa.Data, 20))
  65. }
  66. //
  67. // Accessor
  68. //
  69. type Accessor struct {
  70. Source string
  71. Count int
  72. Stride int
  73. Params []Param
  74. }
  75. // Dump prints out information about the Accessor
  76. func (ac *Accessor) Dump(out io.Writer, indent int) {
  77. fmt.Fprintf(out, "%sAccessor source:%s count:%d stride:%d\n",
  78. sIndent(indent), ac.Source, ac.Count, ac.Stride)
  79. ind := indent + step
  80. for _, p := range ac.Params {
  81. p.Dump(out, ind)
  82. }
  83. }
  84. //
  85. // Param for <bind_material> and <accessor>
  86. //
  87. type Param struct {
  88. Name string
  89. Type string
  90. }
  91. // Dump prints out information about the Param
  92. func (p *Param) Dump(out io.Writer, indent int) {
  93. fmt.Fprintf(out, "%sParam name:%s type:%s\n", sIndent(indent), p.Name, p.Type)
  94. }
  95. // decSource decodes the source from the specified mesh
  96. func (d *Decoder) decSource(start xml.StartElement) (*Source, error) {
  97. // Create source and adds it to the mesh
  98. source := new(Source)
  99. source.Id = findAttrib(start, "id").Value
  100. source.Name = findAttrib(start, "name").Value
  101. // Decodes source children
  102. for {
  103. // Get next child
  104. child, data, err := d.decNextChild(start)
  105. if err != nil || child.Name.Local == "" {
  106. return source, err
  107. }
  108. if child.Name.Local == "float_array" {
  109. err = d.decFloatArray(child, data, source)
  110. if err != nil {
  111. return nil, err
  112. }
  113. continue
  114. }
  115. if child.Name.Local == "Name_array" {
  116. err = d.decNameArray(child, data, source)
  117. if err != nil {
  118. return nil, err
  119. }
  120. continue
  121. }
  122. // Decodes technique_common which should contain an Acessor
  123. if child.Name.Local == "technique_common" {
  124. err = d.decSourceTechniqueCommon(child, source)
  125. if err != nil {
  126. return nil, err
  127. }
  128. continue
  129. }
  130. }
  131. return source, nil
  132. }
  133. // decSource decodes the float array from the specified source
  134. func (d *Decoder) decFloatArray(start xml.StartElement, data []byte, source *Source) error {
  135. // Create float array and associates it to the parent source
  136. farray := &FloatArray{}
  137. farray.Id = findAttrib(start, "id").Value
  138. farray.Count, _ = strconv.Atoi(findAttrib(start, "count").Value)
  139. source.ArrayElement = farray
  140. // Allocates memory for array
  141. farray.Data = make([]float32, farray.Count, farray.Count)
  142. // Reads the numbers from the data
  143. err := decFloat32Sequence(data, farray.Data)
  144. if err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. func (d *Decoder) decNameArray(start xml.StartElement, data []byte, source *Source) error {
  150. narray := new(NameArray)
  151. narray.Id = findAttrib(start, "id").Value
  152. narray.Count, _ = strconv.Atoi(findAttrib(start, "count").Value)
  153. source.ArrayElement = narray
  154. // Allocates memory for array
  155. narray.Data = make([]string, narray.Count, narray.Count)
  156. // Reads the strings from the data
  157. err := decStringSequence(data, narray.Data)
  158. if err != nil {
  159. return err
  160. }
  161. return nil
  162. }
  163. func (d *Decoder) decSourceTechniqueCommon(start xml.StartElement, source *Source) error {
  164. // Decodes source technique common children
  165. for {
  166. // Get next child
  167. child, _, err := d.decNextChild(start)
  168. if err != nil || child.Name.Local == "" {
  169. return err
  170. }
  171. //log.Debug("decSourceTechniqueCommon(%s): %s", start.Name.Local, child.Name.Local)
  172. if child.Name.Local == "accessor" {
  173. err = d.decAcessor(child, source)
  174. if err != nil {
  175. return err
  176. }
  177. continue
  178. }
  179. }
  180. }
  181. // decAcessore decodes the acessor from the specified source
  182. func (d *Decoder) decAcessor(start xml.StartElement, source *Source) error {
  183. // Sets accessor fields
  184. source.TechniqueCommon.Accessor.Source = findAttrib(start, "source").Value
  185. source.TechniqueCommon.Accessor.Count, _ = strconv.Atoi(findAttrib(start, "count").Value)
  186. source.TechniqueCommon.Accessor.Stride, _ = strconv.Atoi(findAttrib(start, "stride").Value)
  187. // Decodes accessor children
  188. for {
  189. // Get next child
  190. child, _, err := d.decNextChild(start)
  191. if err != nil || child.Name.Local == "" {
  192. return err
  193. }
  194. // param
  195. if child.Name.Local == "param" {
  196. err = d.decParam(child, &source.TechniqueCommon.Accessor)
  197. if err != nil {
  198. return err
  199. }
  200. }
  201. }
  202. return nil
  203. }
  204. func (d *Decoder) decParam(start xml.StartElement, accessor *Accessor) error {
  205. p := Param{}
  206. p.Name = findAttrib(start, "name").Value
  207. p.Type = findAttrib(start, "type").Value
  208. accessor.Params = append(accessor.Params, p)
  209. return nil
  210. }
  211. func (d *Decoder) decNextChild(parent xml.StartElement) (xml.StartElement, []byte, error) {
  212. for {
  213. var tok interface{}
  214. var err error
  215. // Reads next token
  216. if d.lastToken == nil {
  217. tok, err = d.xmldec.Token()
  218. if err != nil {
  219. return xml.StartElement{}, nil, err
  220. }
  221. } else {
  222. tok = d.lastToken
  223. d.lastToken = nil
  224. }
  225. // Checks if it is the end element of this parent
  226. el, ok := tok.(xml.EndElement)
  227. if ok {
  228. if el.Name.Local == parent.Name.Local {
  229. return xml.StartElement{}, nil, nil
  230. }
  231. continue
  232. }
  233. // Checks if it is a start element
  234. start, ok := tok.(xml.StartElement)
  235. if !ok {
  236. continue
  237. }
  238. // Get this start element optional char data (should be next token)
  239. tok, err = d.xmldec.Token()
  240. if err != nil {
  241. return xml.StartElement{}, nil, err
  242. }
  243. // If token read is CharData, return the start element and its CharData
  244. cdata, ok := tok.(xml.CharData)
  245. if ok {
  246. return start, cdata, nil
  247. }
  248. // Token read was not CharData and was not processed
  249. // Save it into "lastToken" to be processed at the next call
  250. d.lastToken = tok
  251. return start, nil, nil
  252. }
  253. }
  254. func findAttrib(s xml.StartElement, name string) xml.Attr {
  255. for _, attr := range s.Attr {
  256. if attr.Name.Local == name {
  257. return attr
  258. }
  259. }
  260. return xml.Attr{}
  261. }
  262. const tokenSep string = " \r\n\t"
  263. type bytesReader struct {
  264. pos int
  265. source []byte
  266. }
  267. func (br *bytesReader) Init(source []byte) {
  268. br.pos = 0
  269. br.source = source
  270. }
  271. func (br *bytesReader) TokenNext() []byte {
  272. // Skip leading separators
  273. for br.pos < len(br.source) {
  274. if bytes.IndexByte([]byte(tokenSep), br.source[br.pos]) < 0 {
  275. break
  276. }
  277. br.pos++
  278. }
  279. if br.pos >= len(br.source) {
  280. return nil
  281. }
  282. // Advance till the end of the token
  283. start := br.pos
  284. for br.pos < len(br.source) {
  285. if bytes.IndexByte([]byte(tokenSep), br.source[br.pos]) >= 0 {
  286. break
  287. }
  288. br.pos++
  289. }
  290. res := br.source[start:br.pos]
  291. if len(res) == 0 {
  292. return nil
  293. }
  294. return res
  295. }
  296. const step = 3
  297. func sIndent(indent int) string {
  298. return strings.Repeat(" ", indent)
  299. }
  300. // decFloat32Sequence receives a byte slice with float numbers separated
  301. // by spaces and a preallocated destination slice.
  302. // It reads numbers from the source byte slice, converts them to float32 and
  303. // stores in the destination array.
  304. func decFloat32Sequence(cdata []byte, dest []float32) error {
  305. var br bytesReader
  306. br.Init(cdata)
  307. idx := 0
  308. for {
  309. tok := br.TokenNext()
  310. if tok == nil {
  311. break
  312. }
  313. if idx >= len(dest) {
  314. return fmt.Errorf("To much float array data")
  315. }
  316. v, err := strconv.ParseFloat(string(tok), 32)
  317. if err != nil {
  318. return err
  319. }
  320. dest[idx] = float32(v)
  321. idx++
  322. }
  323. if idx < len(dest)-1 {
  324. return fmt.Errorf("Expected %d floats, got %d", len(dest), idx)
  325. }
  326. return nil
  327. }
  328. // decStringSequence receives a byte slice with strings separated
  329. // by spaces and a preallocated destination slice.
  330. // It reads strings from the source byte slice and
  331. // stores in the destination array.
  332. func decStringSequence(cdata []byte, dest []string) error {
  333. var br bytesReader
  334. br.Init(cdata)
  335. idx := 0
  336. for {
  337. tok := br.TokenNext()
  338. if tok == nil {
  339. break
  340. }
  341. if idx >= len(dest) {
  342. return fmt.Errorf("To many string array data")
  343. }
  344. dest[idx] = string(tok)
  345. idx++
  346. }
  347. if idx < len(dest)-1 {
  348. return fmt.Errorf("Expected %d strings, got %d", len(dest), idx)
  349. }
  350. return nil
  351. }
  352. func f32sToString(a []float32, max int) string {
  353. parts := []string{"["}
  354. if len(a) > max {
  355. for i := 0; i < max/2; i++ {
  356. parts = append(parts, strconv.FormatFloat(float64(a[i]), 'f', -1, 32))
  357. }
  358. parts = append(parts, " ... ")
  359. for i := len(a) - max/2; i < len(a); i++ {
  360. parts = append(parts, strconv.FormatFloat(float64(a[i]), 'f', -1, 32))
  361. }
  362. } else {
  363. for i := 0; i < len(a); i++ {
  364. parts = append(parts, strconv.FormatFloat(float64(a[i]), 'f', -1, 32))
  365. }
  366. }
  367. parts = append(parts, "]")
  368. return strings.Join(parts, " ")
  369. }
  370. func intsToString(a []int, max int) string {
  371. parts := []string{"["}
  372. if len(a) > max {
  373. for i := 0; i < max/2; i++ {
  374. parts = append(parts, strconv.FormatInt(int64(a[i]), 10))
  375. }
  376. parts = append(parts, " ... ")
  377. for i := len(a) - max/2; i < len(a); i++ {
  378. parts = append(parts, strconv.FormatInt(int64(a[i]), 10))
  379. }
  380. } else {
  381. for i := 0; i < len(a); i++ {
  382. parts = append(parts, strconv.FormatInt(int64(a[i]), 10))
  383. }
  384. }
  385. parts = append(parts, "]")
  386. return strings.Join(parts, " ")
  387. }