common.go 9.9 KB

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