Merge branch 'qtquick2' of scm.dev.nokia.troll.no:qt/qtdeclarative-staging into qtquick2
[profile/ivi/qtdeclarative.git] / src / declarative / particles / qsgimageparticle.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the Declarative module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file.  Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 **
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 **
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <private/qsgcontext_p.h>
43 #include <private/qsgadaptationlayer_p.h>
44 #include <qsgnode.h>
45 #include <qsgtexturematerial.h>
46 #include <qsgtexture.h>
47 #include <QFile>
48 #include "qsgimageparticle_p.h"
49 #include "qsgparticleemitter_p.h"
50 #include "qsgsprite_p.h"
51 #include "qsgspriteengine_p.h"
52 #include <QGLFunctions>
53 #include <qsgengine.h>
54
55 QT_BEGIN_NAMESPACE
56
57 const float CONV = 0.017453292519943295;
58 class UltraMaterial : public QSGMaterial
59 {
60 public:
61     UltraMaterial(bool withSprites=false)
62         : timestamp(0)
63         , framecount(1)
64         , animcount(1)
65         , usesSprites(withSprites)
66     {
67         setFlag(Blending, true);
68     }
69
70     ~UltraMaterial()
71     {
72         delete texture;
73         delete colortable;
74         delete sizetable;
75         delete opacitytable;
76     }
77
78     virtual QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
79     virtual QSGMaterialShader *createShader() const;
80     virtual int compare(const QSGMaterial *other) const
81     {
82         return this - static_cast<const UltraMaterial *>(other);
83     }
84
85     QSGTexture *texture;
86     QSGTexture *colortable;
87     QSGTexture *sizetable;
88     QSGTexture *opacitytable;
89
90     qreal timestamp;
91     int framecount;
92     int animcount;
93     bool usesSprites;
94 };
95 class UltraMaterialData : public QSGMaterialShader
96 {
97 public:
98     UltraMaterialData(const char *vertexFile = 0, const char *fragmentFile = 0)
99     {
100         QFile vf(vertexFile ? vertexFile : ":defaultshaders/ultravertex.shader");
101         vf.open(QFile::ReadOnly);
102         m_vertex_code = vf.readAll();
103
104         QFile ff(fragmentFile ? fragmentFile : ":defaultshaders/ultrafragment.shader");
105         ff.open(QFile::ReadOnly);
106         m_fragment_code = ff.readAll();
107
108         Q_ASSERT(!m_vertex_code.isNull());
109         Q_ASSERT(!m_fragment_code.isNull());
110     }
111
112     void deactivate() {
113         QSGMaterialShader::deactivate();
114
115         for (int i=0; i<8; ++i) {
116             program()->setAttributeArray(i, GL_FLOAT, chunkOfBytes, 1, 0);
117         }
118     }
119
120     virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
121     {
122         UltraMaterial *m = static_cast<UltraMaterial *>(newEffect);
123         state.context()->functions()->glActiveTexture(GL_TEXTURE1);
124         m->colortable->bind();
125         program()->setUniformValue(m_colortable_id, 1);
126
127         state.context()->functions()->glActiveTexture(GL_TEXTURE2);
128         m->sizetable->bind();
129         program()->setUniformValue(m_sizetable_id, 2);
130
131         state.context()->functions()->glActiveTexture(GL_TEXTURE3);
132         m->opacitytable->bind();
133         program()->setUniformValue(m_opacitytable_id, 3);
134
135         state.context()->functions()->glActiveTexture(GL_TEXTURE0);//Investigate why this screws up Text{} if placed before 1
136         m->texture->bind();
137
138         program()->setUniformValue(m_opacity_id, state.opacity());
139         program()->setUniformValue(m_timestamp_id, (float) m->timestamp);
140         program()->setUniformValue(m_framecount_id, (float) m->framecount);
141         program()->setUniformValue(m_animcount_id, (float) m->animcount);
142
143         if (state.isMatrixDirty())
144             program()->setUniformValue(m_matrix_id, state.combinedMatrix());
145     }
146
147     virtual void initialize() {
148         m_colortable_id = program()->uniformLocation("colortable");
149         m_sizetable_id = program()->uniformLocation("sizetable");
150         m_opacitytable_id = program()->uniformLocation("opacitytable");
151         m_matrix_id = program()->uniformLocation("matrix");
152         m_opacity_id = program()->uniformLocation("opacity");
153         m_timestamp_id = program()->uniformLocation("timestamp");
154         m_framecount_id = program()->uniformLocation("framecount");
155         m_animcount_id = program()->uniformLocation("animcount");
156     }
157
158     virtual const char *vertexShader() const { return m_vertex_code.constData(); }
159     virtual const char *fragmentShader() const { return m_fragment_code.constData(); }
160
161     virtual char const *const *attributeNames() const {
162         static const char *attr[] = {
163             "vPos",
164             "vTex",
165             "vData",
166             "vVec",
167             "vColor",
168             "vDeformVec",
169             "vRotation",
170             "vAnimData",
171             0
172         };
173         return attr;
174     }
175
176     virtual bool isColorTable() const { return false; }
177
178     int m_matrix_id;
179     int m_opacity_id;
180     int m_timestamp_id;
181     int m_colortable_id;
182     int m_sizetable_id;
183     int m_opacitytable_id;
184     int m_framecount_id;
185     int m_animcount_id;
186
187     QByteArray m_vertex_code;
188     QByteArray m_fragment_code;
189
190     static float chunkOfBytes[1024];
191 };
192 float UltraMaterialData::chunkOfBytes[1024];
193
194 QSGMaterialShader *UltraMaterial::createShader() const
195 {
196     if(usesSprites)//TODO: Perhaps just swap the shaders, and don't mind the extra vector?
197         return new UltraMaterialData;
198     else
199         return new UltraMaterialData;
200 }
201
202
203 class SimpleMaterial : public UltraMaterial
204 {
205     virtual QSGMaterialShader *createShader() const;
206     virtual QSGMaterialType *type() const { static QSGMaterialType type; return &type; }
207 };
208
209 class SimpleMaterialData : public QSGMaterialShader
210 {
211 public:
212     SimpleMaterialData(const char *vertexFile = 0, const char *fragmentFile = 0)
213     {
214         QFile vf(vertexFile ? vertexFile : ":defaultshaders/simplevertex.shader");
215         vf.open(QFile::ReadOnly);
216         m_vertex_code = vf.readAll();
217
218         QFile ff(fragmentFile ? fragmentFile : ":defaultshaders/simplefragment.shader");
219         ff.open(QFile::ReadOnly);
220         m_fragment_code = ff.readAll();
221
222         Q_ASSERT(!m_vertex_code.isNull());
223         Q_ASSERT(!m_fragment_code.isNull());
224     }
225
226     void deactivate() {
227         QSGMaterialShader::deactivate();
228
229         for (int i=0; i<8; ++i) {
230             program()->setAttributeArray(i, GL_FLOAT, chunkOfBytes, 1, 0);
231         }
232     }
233
234     virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *)
235     {
236         UltraMaterial *m = static_cast<UltraMaterial *>(newEffect);
237         state.context()->functions()->glActiveTexture(GL_TEXTURE0);
238         m->texture->bind();
239
240         program()->setUniformValue(m_opacity_id, state.opacity());
241         program()->setUniformValue(m_timestamp_id, (float) m->timestamp);
242
243         if (state.isMatrixDirty())
244             program()->setUniformValue(m_matrix_id, state.combinedMatrix());
245     }
246
247     virtual void initialize() {
248         m_matrix_id = program()->uniformLocation("matrix");
249         m_opacity_id = program()->uniformLocation("opacity");
250         m_timestamp_id = program()->uniformLocation("timestamp");
251     }
252
253     virtual const char *vertexShader() const { return m_vertex_code.constData(); }
254     virtual const char *fragmentShader() const { return m_fragment_code.constData(); }
255
256     virtual char const *const *attributeNames() const {
257         static const char *attr[] = {
258             "vPos",
259             "vTex",
260             "vData",
261             "vVec",
262             0
263         };
264         return attr;
265     }
266
267     virtual bool isColorTable() const { return false; }
268
269     int m_matrix_id;
270     int m_opacity_id;
271     int m_timestamp_id;
272
273     QByteArray m_vertex_code;
274     QByteArray m_fragment_code;
275
276     static float chunkOfBytes[1024];
277 };
278 float SimpleMaterialData::chunkOfBytes[1024];
279
280 QSGMaterialShader *SimpleMaterial::createShader() const {
281     return new SimpleMaterialData;
282 }
283
284 QSGImageParticle::QSGImageParticle(QSGItem* parent)
285     : QSGParticlePainter(parent)
286     , m_do_reset(false)
287     , m_color_variation(0.0)
288     , m_node(0)
289     , m_material(0)
290     , m_alphaVariation(0.0)
291     , m_alpha(1.0)
292     , m_redVariation(0.0)
293     , m_greenVariation(0.0)
294     , m_blueVariation(0.0)
295     , m_rotation(0)
296     , m_autoRotation(false)
297     , m_xVector(0)
298     , m_yVector(0)
299     , m_rotationVariation(0)
300     , m_rotationSpeed(0)
301     , m_rotationSpeedVariation(0)
302     , m_spriteEngine(0)
303     , m_bloat(false)
304     , perfLevel(Unknown)
305     , m_lastLevel(Unknown)
306 {
307     setFlag(ItemHasContents);
308 }
309
310 QDeclarativeListProperty<QSGSprite> QSGImageParticle::sprites()
311 {
312     return QDeclarativeListProperty<QSGSprite>(this, &m_sprites, spriteAppend, spriteCount, spriteAt, spriteClear);
313 }
314
315 void QSGImageParticle::setImage(const QUrl &image)
316 {
317     if (image == m_image_name)
318         return;
319     m_image_name = image;
320     emit imageChanged();
321     reset();
322 }
323
324
325 void QSGImageParticle::setColortable(const QUrl &table)
326 {
327     if (table == m_colortable_name)
328         return;
329     m_colortable_name = table;
330     emit colortableChanged();
331     reset();
332 }
333
334 void QSGImageParticle::setSizetable(const QUrl &table)
335 {
336     if (table == m_sizetable_name)
337         return;
338     m_sizetable_name = table;
339     emit sizetableChanged();
340     reset();
341 }
342
343 void QSGImageParticle::setOpacitytable(const QUrl &table)
344 {
345     if (table == m_opacitytable_name)
346         return;
347     m_opacitytable_name = table;
348     emit opacitytableChanged();
349     reset();
350 }
351
352 void QSGImageParticle::setColor(const QColor &color)
353 {
354     if (color == m_color)
355         return;
356     m_color = color;
357     emit colorChanged();
358     if(perfLevel < Coloured)
359         reset();
360 }
361
362 void QSGImageParticle::setColorVariation(qreal var)
363 {
364     if (var == m_color_variation)
365         return;
366     m_color_variation = var;
367     emit colorVariationChanged();
368     if(perfLevel < Coloured)
369         reset();
370 }
371
372 void QSGImageParticle::setAlphaVariation(qreal arg)
373 {
374     if (m_alphaVariation != arg) {
375         m_alphaVariation = arg;
376         emit alphaVariationChanged(arg);
377     }
378     if(perfLevel < Coloured)
379         reset();
380 }
381
382 void QSGImageParticle::setAlpha(qreal arg)
383 {
384     if (m_alpha != arg) {
385         m_alpha = arg;
386         emit alphaChanged(arg);
387     }
388     if(perfLevel < Coloured)
389         reset();
390 }
391
392 void QSGImageParticle::setRedVariation(qreal arg)
393 {
394     if (m_redVariation != arg) {
395         m_redVariation = arg;
396         emit redVariationChanged(arg);
397     }
398     if(perfLevel < Coloured)
399         reset();
400 }
401
402 void QSGImageParticle::setGreenVariation(qreal arg)
403 {
404     if (m_greenVariation != arg) {
405         m_greenVariation = arg;
406         emit greenVariationChanged(arg);
407     }
408     if(perfLevel < Coloured)
409         reset();
410 }
411
412 void QSGImageParticle::setBlueVariation(qreal arg)
413 {
414     if (m_blueVariation != arg) {
415         m_blueVariation = arg;
416         emit blueVariationChanged(arg);
417     }
418     if(perfLevel < Coloured)
419         reset();
420 }
421
422 void QSGImageParticle::setRotation(qreal arg)
423 {
424     if (m_rotation != arg) {
425         m_rotation = arg;
426         emit rotationChanged(arg);
427     }
428     if(perfLevel < Deformable)
429         reset();
430 }
431
432 void QSGImageParticle::setRotationVariation(qreal arg)
433 {
434     if (m_rotationVariation != arg) {
435         m_rotationVariation = arg;
436         emit rotationVariationChanged(arg);
437     }
438     if(perfLevel < Deformable)
439         reset();
440 }
441
442 void QSGImageParticle::setRotationSpeed(qreal arg)
443 {
444     if (m_rotationSpeed != arg) {
445         m_rotationSpeed = arg;
446         emit rotationSpeedChanged(arg);
447     }
448     if(perfLevel < Deformable)
449         reset();
450 }
451
452 void QSGImageParticle::setRotationSpeedVariation(qreal arg)
453 {
454     if (m_rotationSpeedVariation != arg) {
455         m_rotationSpeedVariation = arg;
456         emit rotationSpeedVariationChanged(arg);
457     }
458     if(perfLevel < Deformable)
459         reset();
460 }
461
462 void QSGImageParticle::setAutoRotation(bool arg)
463 {
464     if (m_autoRotation != arg) {
465         m_autoRotation = arg;
466         emit autoRotationChanged(arg);
467     }
468     if(perfLevel < Deformable)
469         reset();
470 }
471
472 void QSGImageParticle::setXVector(QSGStochasticDirection* arg)
473 {
474     if (m_xVector != arg) {
475         m_xVector = arg;
476         emit xVectorChanged(arg);
477     }
478     if(perfLevel < Deformable)
479         reset();
480 }
481
482 void QSGImageParticle::setYVector(QSGStochasticDirection* arg)
483 {
484     if (m_yVector != arg) {
485         m_yVector = arg;
486         emit yVectorChanged(arg);
487     }
488     if(perfLevel < Deformable)
489         reset();
490 }
491
492 void QSGImageParticle::setBloat(bool arg)
493 {
494     if (m_bloat != arg) {
495         m_bloat = arg;
496         emit bloatChanged(arg);
497     }
498     if(perfLevel < 9999)
499         reset();
500 }
501 void QSGImageParticle::setCount(int c)
502 {
503     QSGParticlePainter::setCount(c);
504     m_pleaseReset = true;
505 }
506
507 void QSGImageParticle::reset()
508 {
509     QSGParticlePainter::reset();
510      m_pleaseReset = true;
511 }
512
513 void QSGImageParticle::createEngine()
514 {
515     if(m_spriteEngine)
516         delete m_spriteEngine;
517     if(m_sprites.count())
518         m_spriteEngine = new QSGSpriteEngine(m_sprites, this);
519     else
520         m_spriteEngine = 0;
521     reset();
522 }
523
524 static QSGGeometry::Attribute SimpleParticle_Attributes[] = {
525     { 0, 2, GL_FLOAT },             // Position
526     { 1, 2, GL_FLOAT },             // TexCoord
527     { 2, 4, GL_FLOAT },             // Data
528     { 3, 4, GL_FLOAT }             // Vectors
529 };
530
531 static QSGGeometry::AttributeSet SimpleParticle_AttributeSet =
532 {
533     4, // Attribute Count
534     (2 + 2 + 4 + 4 ) * sizeof(float),
535     SimpleParticle_Attributes
536 };
537
538 static QSGGeometry::Attribute UltraParticle_Attributes[] = {
539     { 0, 2, GL_FLOAT },             // Position
540     { 1, 2, GL_FLOAT },             // TexCoord
541     { 2, 4, GL_FLOAT },             // Data
542     { 3, 4, GL_FLOAT },             // Vectors
543     { 4, 4, GL_UNSIGNED_BYTE },     // Colors
544     { 5, 4, GL_FLOAT },             // DeformationVectors
545     { 6, 3, GL_FLOAT },             // Rotation
546     { 7, 4, GL_FLOAT }              // Anim Data
547 };
548
549 static QSGGeometry::AttributeSet UltraParticle_AttributeSet =
550 {
551     8, // Attribute Count
552     (2 + 2 + 4 + 4 + 4 + 4 + 3) * sizeof(float) + 4 * sizeof(uchar),
553     UltraParticle_Attributes
554 };
555
556 QSGGeometryNode* QSGImageParticle::buildSimpleParticleNode()
557 {
558     perfLevel = Simple;//TODO: Intermediate levels
559     QImage image = QImage(m_image_name.toLocalFile());
560     if (image.isNull()) {
561         printf("UltraParticle: loading image failed... '%s'\n", qPrintable(m_image_name.toLocalFile()));
562         return 0;
563     }
564     int vCount = m_count * 4;
565     int iCount = m_count * 6;
566     qDebug() << "Simple Case";
567
568     QSGGeometry *g = new QSGGeometry(SimpleParticle_AttributeSet, vCount, iCount);
569     g->setDrawingMode(GL_TRIANGLES);
570
571     SimpleVertex *vertices = (SimpleVertex *) g->vertexData();
572     for (int p=0; p<m_count; ++p) {
573         for (int i=0; i<4; ++i) {
574             vertices[i].x = 0;
575             vertices[i].y = 0;
576             vertices[i].t = -1;
577             vertices[i].lifeSpan = 0;
578             vertices[i].size = 0;
579             vertices[i].endSize = 0;
580             vertices[i].sx = 0;
581             vertices[i].sy = 0;
582             vertices[i].ax = 0;
583             vertices[i].ay = 0;
584         }
585
586         vertices[0].tx = 0;
587         vertices[0].ty = 0;
588
589         vertices[1].tx = 1;
590         vertices[1].ty = 0;
591
592         vertices[2].tx = 0;
593         vertices[2].ty = 1;
594
595         vertices[3].tx = 1;
596         vertices[3].ty = 1;
597
598         vertices += 4;
599     }
600
601     quint16 *indices = g->indexDataAsUShort();
602     for (int i=0; i<m_count; ++i) {
603         int o = i * 4;
604         indices[0] = o;
605         indices[1] = o + 1;
606         indices[2] = o + 2;
607         indices[3] = o + 1;
608         indices[4] = o + 3;
609         indices[5] = o + 2;
610         indices += 6;
611     }
612
613     if (m_material) {
614         delete m_material;
615         m_material = 0;
616     }
617
618     m_material = new SimpleMaterial();
619     m_material->texture = sceneGraphEngine()->createTextureFromImage(image);
620     m_material->texture->setFiltering(QSGTexture::Linear);
621     m_material->framecount = 1;
622     m_node = new QSGGeometryNode();
623     m_node->setGeometry(g);
624     m_node->setMaterial(m_material);
625
626     m_last_particle = 0;
627
628     return m_node;
629 }
630
631 QSGGeometryNode* QSGImageParticle::buildParticleNode()
632 {
633     if (m_count * 4 > 0xffff) {
634         printf("UltraParticle: Too many particles... \n");//####Why is this here?
635         return 0;
636     }
637
638     if(m_count <= 0) {
639         printf("UltraParticle: Too few particles... \n");
640         return 0;
641     }
642
643     if(!m_sprites.count() && !m_bloat
644             && m_colortable_name.isEmpty()
645             && m_sizetable_name.isEmpty()
646             && m_opacitytable_name.isEmpty()
647             && !m_autoRotation
648             && !m_rotation && !m_rotationVariation
649             && !m_rotationSpeed && !m_rotationSpeedVariation
650             && !m_alphaVariation && m_alpha == 1.0
651             && !m_redVariation && !m_blueVariation && !m_greenVariation
652             && !m_color.isValid()
653             )
654         return buildSimpleParticleNode();
655     perfLevel = Sprites;//TODO: intermediate levels
656     if(!m_color.isValid())//But we're in colored level (or higher)
657         m_color = QColor(Qt::white);
658     qDebug() << "Complex Case";
659
660     QImage image;
661     if(m_sprites.count()){
662         if (!m_spriteEngine) {
663             qWarning() << "UltraParticle: No sprite engine...";
664             return 0;
665         }
666         image = m_spriteEngine->assembledImage();
667         if(image.isNull())//Warning is printed in engine
668             return 0;
669     }else{
670         image = QImage(m_image_name.toLocalFile());
671         if (image.isNull()) {
672             printf("UltraParticle: loading image failed... '%s'\n", qPrintable(m_image_name.toLocalFile()));
673             return 0;
674         }
675     }
676
677     int vCount = m_count * 4;
678     int iCount = m_count * 6;
679
680     QSGGeometry *g = new QSGGeometry(UltraParticle_AttributeSet, vCount, iCount);
681     g->setDrawingMode(GL_TRIANGLES);
682
683     UltraVertex *vertices = (UltraVertex *) g->vertexData();
684     SimpleVertex *oldSimple = (SimpleVertex *) m_lastData;//TODO: Other levels
685     if(m_lastLevel == 1)
686         qDebug() << "Theta" << m_lastLevel << oldSimple[0].x << oldSimple[0].y << oldSimple[0].t;
687     for (int p=0; p<m_count; ++p) {
688
689         if (m_lastLevel == 1) {//Transplant/IntermediateVertices?
690             for (int i=0; i<4; ++i) {
691                 vertices[i].x = oldSimple[i].x;
692                 vertices[i].y = oldSimple[i].y;
693                 vertices[i].t = oldSimple[i].t;
694                 vertices[i].lifeSpan = oldSimple[i].lifeSpan;
695                 vertices[i].size = oldSimple[i].size;
696                 vertices[i].endSize = oldSimple[i].endSize;
697                 vertices[i].sx = oldSimple[i].sx;
698                 vertices[i].sy = oldSimple[i].sy;
699                 vertices[i].ax = oldSimple[i].ax;
700                 vertices[i].ay = oldSimple[i].ay;
701                 vertices[i].xx = 1;
702                 vertices[i].xy = 0;
703                 vertices[i].yx = 0;
704                 vertices[i].yy = 1;
705                 vertices[i].rotation = 0;
706                 vertices[i].rotationSpeed = 0;
707                 vertices[i].autoRotate = 0;
708                 vertices[i].animIdx = 0;
709                 vertices[i].frameDuration = oldSimple[i].lifeSpan;
710                 vertices[i].frameCount = 1;
711                 vertices[i].animT = oldSimple[i].t;
712                 vertices[i].color.r = 255;
713                 vertices[i].color.g = 255;
714                 vertices[i].color.b = 255;
715                 vertices[i].color.a = 255;
716             }
717         } else {
718             for (int i=0; i<4; ++i) {
719                 vertices[i].x = 0;
720                 vertices[i].y = 0;
721                 vertices[i].t = -1;
722                 vertices[i].lifeSpan = 0;
723                 vertices[i].size = 0;
724                 vertices[i].endSize = 0;
725                 vertices[i].sx = 0;
726                 vertices[i].sy = 0;
727                 vertices[i].ax = 0;
728                 vertices[i].ay = 0;
729                 vertices[i].xx = 1;
730                 vertices[i].xy = 0;
731                 vertices[i].yx = 0;
732                 vertices[i].yy = 1;
733                 vertices[i].rotation = 0;
734                 vertices[i].rotationSpeed = 0;
735                 vertices[i].autoRotate = 0;
736                 vertices[i].animIdx = -1;
737                 vertices[i].frameDuration = 1;
738                 vertices[i].frameCount = 0;
739                 vertices[i].animT = -1;
740                 vertices[i].color.r = 0;//TODO:Some things never get used uninitialized. Consider dropping them here?
741                 vertices[i].color.g = 0;
742                 vertices[i].color.b = 0;
743                 vertices[i].color.a = 0;
744             }
745         }
746
747         vertices[0].tx = 0;
748         vertices[0].ty = 0;
749
750         vertices[1].tx = 1;
751         vertices[1].ty = 0;
752
753         vertices[2].tx = 0;
754         vertices[2].ty = 1;
755
756         vertices[3].tx = 1;
757         vertices[3].ty = 1;
758
759         vertices += 4;
760         oldSimple += 4;
761     }
762
763     quint16 *indices = g->indexDataAsUShort();//TODO: Speed gains by copying this over if count unchanged?
764     for (int i=0; i<m_count; ++i) {
765         int o = i * 4;
766         indices[0] = o;
767         indices[1] = o + 1;
768         indices[2] = o + 2;
769         indices[3] = o + 1;
770         indices[4] = o + 3;
771         indices[5] = o + 2;
772         indices += 6;
773     }
774
775     qFree(m_lastData);
776     if (m_material) {
777         delete m_material;
778         m_material = 0;
779     }
780
781     QImage colortable(m_colortable_name.toLocalFile());
782     QImage sizetable(m_sizetable_name.toLocalFile());
783     QImage opacitytable(m_opacitytable_name.toLocalFile());
784     m_material = new UltraMaterial();
785     if(colortable.isNull())
786         colortable = QImage(":defaultshaders/identitytable.png");
787     if(sizetable.isNull())
788         sizetable = QImage(":defaultshaders/identitytable.png");
789     if(opacitytable.isNull())
790         opacitytable = QImage(":defaultshaders/defaultFadeInOut.png");
791     Q_ASSERT(!colortable.isNull());
792     Q_ASSERT(!sizetable.isNull());
793     Q_ASSERT(!opacitytable.isNull());
794     m_material->colortable = sceneGraphEngine()->createTextureFromImage(colortable);
795     m_material->sizetable = sceneGraphEngine()->createTextureFromImage(sizetable);
796     m_material->opacitytable = sceneGraphEngine()->createTextureFromImage(opacitytable);
797
798     m_material->texture = sceneGraphEngine()->createTextureFromImage(image);
799     m_material->texture->setFiltering(QSGTexture::Linear);
800
801     m_material->framecount = 1;
802     if(m_spriteEngine){
803         m_material->framecount = m_spriteEngine->maxFrames();
804         m_spriteEngine->setCount(m_count);
805     }
806
807     m_node = new QSGGeometryNode();
808     m_node->setGeometry(g);
809     m_node->setMaterial(m_material);
810
811     m_last_particle = 0;
812
813     return m_node;
814 }
815
816 QSGNode *QSGImageParticle::updatePaintNode(QSGNode *, UpdatePaintNodeData *)
817 {
818     if(m_pleaseReset){
819         if(m_node){
820             if(perfLevel == 1){
821                 qDebug() << "Beta";
822                 m_lastData = qMalloc(m_count*sizeof(SimpleVertices));//TODO: Account for count_changed possibility
823                 memcpy(m_lastData, m_node->geometry()->vertexData(), m_count * sizeof(SimpleVertices));//TODO: Multiple levels
824             }
825             m_lastLevel = perfLevel;
826             delete m_node;
827         }
828         if(m_material)
829             delete m_material;
830
831         m_node = 0;
832         m_material = 0;
833         m_pleaseReset = false;
834     }
835
836     if(m_system && m_system->isRunning())
837         prepareNextFrame();
838     if (m_node){
839         update();
840         m_node->markDirty(QSGNode::DirtyMaterial);
841     }
842
843     return m_node;
844 }
845
846 void QSGImageParticle::prepareNextFrame()
847 {
848     if (m_node == 0){    //TODO: Staggered loading (as emitted)
849         m_node = buildParticleNode();
850         if(m_node == 0)
851             return;
852         qDebug() << "Feature level: " << perfLevel;
853     }
854     qint64 timeStamp = m_system->systemSync(this);
855
856     qreal time = timeStamp / 1000.;
857     m_material->timestamp = time;
858
859     //Advance State
860     if(m_spriteEngine){//perfLevel == Sprites?
861         m_material->animcount = m_spriteEngine->spriteCount();
862         UltraVertices *particles = (UltraVertices *) m_node->geometry()->vertexData();
863         m_spriteEngine->updateSprites(timeStamp);
864         for(int i=0; i<m_count; i++){
865             UltraVertices &p = particles[i];
866             int curIdx = m_spriteEngine->spriteState(i);
867             if(curIdx != p.v1.animIdx){
868                 p.v1.animIdx = p.v2.animIdx = p.v3.animIdx = p.v4.animIdx = curIdx;
869                 p.v1.animT = p.v2.animT = p.v3.animT = p.v4.animT = m_spriteEngine->spriteStart(i)/1000.0;
870                 p.v1.frameCount = p.v2.frameCount = p.v3.frameCount = p.v4.frameCount = m_spriteEngine->spriteFrames(i);
871                 p.v1.frameDuration = p.v2.frameDuration = p.v3.frameDuration = p.v4.frameDuration = m_spriteEngine->spriteDuration(i);
872             }
873         }
874     }else{
875         m_material->animcount = 1;
876     }
877 }
878
879 template <typename VT>
880 IntermediateVertices* transplant(IntermediateVertices* iv, VT &v)
881 {//Deliberate typemangling cast
882     iv->v1 = (UltraVertex*)&(v.v1);
883     iv->v2 = (UltraVertex*)&(v.v2);
884     iv->v3 = (UltraVertex*)&(v.v3);
885     iv->v4 = (UltraVertex*)&(v.v4);
886     return iv;
887 }
888
889 IntermediateVertices* QSGImageParticle::fetchIntermediateVertices(int pos)
890 {
891     //Note that this class ruins typesafety for you. Maybe even thread safety.
892     //TODO: Something better, possibly with templates or inheritance
893     static IntermediateVertices iv;
894     SimpleVertices *sv;
895     UltraVertices *uv;
896     switch(perfLevel){
897         case Simple:
898             sv = (SimpleVertices *) m_node->geometry()->vertexData();
899             return transplant(&iv, sv[pos]);
900         case Coloured:
901         case Deformable:
902         case Tabled:
903         case Sprites:
904         default:
905             uv = (UltraVertices *) m_node->geometry()->vertexData();
906             return transplant(&iv,uv[pos]);
907     }
908 }
909
910 void QSGImageParticle::reloadColor(const Color4ub &c, QSGParticleData* d)
911 {
912     UltraVertices *particles = (UltraVertices *) m_node->geometry()->vertexData();
913     int pos = particleTypeIndex(d);
914     UltraVertices &p = particles[pos];
915     p.v1.color = p.v2.color = p.v3.color = p.v4.color = c;
916 }
917
918 void QSGImageParticle::reload(QSGParticleData *d)
919 {
920     if (m_node == 0)
921         return;
922
923     int pos = particleTypeIndex(d);
924     IntermediateVertices* p = fetchIntermediateVertices(pos);
925
926     //Perhaps we could be more efficient?
927     vertexCopy(*p->v1, d->pv);
928     vertexCopy(*p->v2, d->pv);
929     vertexCopy(*p->v3, d->pv);
930     vertexCopy(*p->v4, d->pv);
931 }
932
933 void QSGImageParticle::load(QSGParticleData *d)
934 {
935     if (m_node == 0)
936         return;
937
938     int pos = particleTypeIndex(d);
939     IntermediateVertices* p = fetchIntermediateVertices(pos);//Remember this removes typesafety!
940     Color4ub color;
941     qreal redVariation = m_color_variation + m_redVariation;
942     qreal greenVariation = m_color_variation + m_greenVariation;
943     qreal blueVariation = m_color_variation + m_blueVariation;
944     switch(perfLevel){//Fall-through is intended on all of them
945         case Sprites:
946             // Initial Sprite State
947             p->v1->animT = p->v2->animT = p->v3->animT = p->v4->animT = p->v1->t;
948             p->v1->animIdx = p->v2->animIdx = p->v3->animIdx = p->v4->animIdx = 0;
949             if(m_spriteEngine){
950                 m_spriteEngine->startSprite(pos);
951                 p->v1->frameCount = p->v2->frameCount = p->v3->frameCount = p->v4->frameCount = m_spriteEngine->spriteFrames(pos);
952                 p->v1->frameDuration = p->v2->frameDuration = p->v3->frameDuration = p->v4->frameDuration = m_spriteEngine->spriteDuration(pos);
953             }else{
954                 p->v1->frameCount = p->v2->frameCount = p->v3->frameCount = p->v4->frameCount = 1;
955                 p->v1->frameDuration = p->v2->frameDuration = p->v3->frameDuration = p->v4->frameDuration = 9999;
956             }
957         case Tabled:
958         case Deformable:
959             //Initial Rotation
960             if(m_xVector){
961                 const QPointF &ret = m_xVector->sample(QPointF(d->pv.x, d->pv.y));
962                 p->v1->xx = p->v2->xx = p->v3->xx = p->v4->xx = ret.x();
963                 p->v1->xy = p->v2->xy = p->v3->xy = p->v4->xy = ret.y();
964             }
965             if(m_yVector){
966                 const QPointF &ret = m_yVector->sample(QPointF(d->pv.x, d->pv.y));
967                 p->v1->yx = p->v2->yx = p->v3->yx = p->v4->yx = ret.x();
968                 p->v1->yy = p->v2->yy = p->v3->yy = p->v4->yy = ret.y();
969             }
970             p->v1->rotation = p->v2->rotation = p->v3->rotation = p->v4->rotation =
971                     (m_rotation + (m_rotationVariation - 2*((qreal)rand()/RAND_MAX)*m_rotationVariation) ) * CONV;
972             p->v1->rotationSpeed = p->v2->rotationSpeed = p->v3->rotationSpeed = p->v4->rotationSpeed =
973                     (m_rotationSpeed + (m_rotationSpeedVariation - 2*((qreal)rand()/RAND_MAX)*m_rotationSpeedVariation) ) * CONV;
974             p->v1->autoRotate = p->v2->autoRotate = p->v3->autoRotate = p->v4->autoRotate = m_autoRotation?1.0:0.0;
975         case Coloured:
976             //Color initialization
977             // Particle color
978             color.r = m_color.red() * (1 - redVariation) + rand() % 256 * redVariation;
979             color.g = m_color.green() * (1 - greenVariation) + rand() % 256 * greenVariation;
980             color.b = m_color.blue() * (1 - blueVariation) + rand() % 256 * blueVariation;
981             color.a = m_alpha * m_color.alpha() * (1 - m_alphaVariation) + rand() % 256 * m_alphaVariation;
982             p->v1->color = p->v2->color = p->v3->color = p->v4->color = color;
983         default:
984             break;
985     }
986
987     vertexCopy(*p->v1, d->pv);
988     vertexCopy(*p->v2, d->pv);
989     vertexCopy(*p->v3, d->pv);
990     vertexCopy(*p->v4, d->pv);
991 }
992
993 QT_END_NAMESPACE