quiet some clang warnings & fix for bugs in exceptional cases.
[blender.git] / source / blender / blenkernel / intern / pointcache.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Campbell Barton <ideasman42@gmail.com>
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/pointcache.c
29  *  \ingroup bke
30  */
31
32
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_ID.h"
42 #include "DNA_cloth_types.h"
43 #include "DNA_modifier_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_object_force.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_smoke_types.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_threads.h"
52 #include "BLI_math.h"
53 #include "BLI_utildefines.h"
54
55 #include "PIL_time.h"
56
57 #include "WM_api.h"
58
59 #include "BKE_anim.h"
60 #include "BKE_blender.h"
61 #include "BKE_cloth.h"
62 #include "BKE_depsgraph.h"
63 #include "BKE_global.h"
64 #include "BKE_library.h"
65 #include "BKE_main.h"
66 #include "BKE_object.h"
67 #include "BKE_particle.h"
68 #include "BKE_pointcache.h"
69 #include "BKE_scene.h"
70 #include "BKE_smoke.h"
71 #include "BKE_softbody.h"
72 #include "BKE_utildefines.h"
73
74 #include "BIK_api.h"
75
76 /* both in intern */
77 #include "smoke_API.h"
78
79 #ifdef WITH_LZO
80 #include "minilzo.h"
81 #else
82 /* used for non-lzo cases */
83 #define LZO_OUT_LEN(size)     ((size) + (size) / 16 + 64 + 3)
84 #endif
85
86 #ifdef WITH_LZMA
87 #include "LzmaLib.h"
88 #endif
89
90 /* needed for directory lookup */
91 /* untitled blend's need getpid for a unique name */
92 #ifndef WIN32
93   #include <dirent.h>
94 #include <unistd.h>
95 #else
96 #include <process.h>
97   #include "BLI_winstuff.h"
98 #endif
99
100 #define PTCACHE_DATA_FROM(data, type, from)             if(data[type]) { memcpy(data[type], from, ptcache_data_size[type]); }
101 #define PTCACHE_DATA_TO(data, type, index, to)  if(data[type]) { memcpy(to, (char*)data[type] + (index ? index * ptcache_data_size[type] : 0), ptcache_data_size[type]); }
102
103 /* could be made into a pointcache option */
104 #define DURIAN_POINTCACHE_LIB_OK 1
105
106 static int ptcache_data_size[] = {      
107                 sizeof(unsigned int), // BPHYS_DATA_INDEX
108                 3 * sizeof(float), // BPHYS_DATA_LOCATION
109                 3 * sizeof(float), // BPHYS_DATA_VELOCITY
110                 4 * sizeof(float), // BPHYS_DATA_ROTATION
111                 3 * sizeof(float), // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST
112                 sizeof(float), // BPHYS_DATA_SIZE
113                 3 * sizeof(float), // BPHYS_DATA_TIMES
114                 sizeof(BoidData) // case BPHYS_DATA_BOIDS
115 };
116
117 static int ptcache_extra_datasize[] = {
118         0,
119         sizeof(ParticleSpring)
120 };
121
122 /* forward declerations */
123 static int ptcache_file_compressed_read(PTCacheFile *pf, unsigned char *result, unsigned int len);
124 static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, unsigned int in_len, unsigned char *out, int mode);
125 static int ptcache_file_write(PTCacheFile *pf, void *f, unsigned int tot, unsigned int size);
126 static int ptcache_file_read(PTCacheFile *pf, void *f, unsigned int tot, unsigned int size);
127
128 /* Common functions */
129 static int ptcache_basic_header_read(PTCacheFile *pf)
130 {
131         int error=0;
132
133         /* Custom functions should read these basic elements too! */
134         if(!error && !fread(&pf->totpoint, sizeof(unsigned int), 1, pf->fp))
135                 error = 1;
136         
137         if(!error && !fread(&pf->data_types, sizeof(unsigned int), 1, pf->fp))
138                 error = 1;
139
140         return !error;
141 }
142 static int ptcache_basic_header_write(PTCacheFile *pf)
143 {
144         /* Custom functions should write these basic elements too! */
145         if(!fwrite(&pf->totpoint, sizeof(unsigned int), 1, pf->fp))
146                 return 0;
147         
148         if(!fwrite(&pf->data_types, sizeof(unsigned int), 1, pf->fp))
149                 return 0;
150
151         return 1;
152 }
153 /* Softbody functions */
154 static int  ptcache_softbody_write(int index, void *soft_v, void **data, int UNUSED(cfra))
155 {
156         SoftBody *soft= soft_v;
157         BodyPoint *bp = soft->bpoint + index;
158
159         PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, bp->pos);
160         PTCACHE_DATA_FROM(data, BPHYS_DATA_VELOCITY, bp->vec);
161
162         return 1;
163 }
164 static void ptcache_softbody_read(int index, void *soft_v, void **data, float UNUSED(cfra), float *old_data)
165 {
166         SoftBody *soft= soft_v;
167         BodyPoint *bp = soft->bpoint + index;
168
169         if(old_data) {
170                 memcpy(bp->pos, data, 3 * sizeof(float));
171                 memcpy(bp->vec, data + 3, 3 * sizeof(float));
172         }
173         else {
174                 PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, 0, bp->pos);
175                 PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, 0, bp->vec);
176         }
177 }
178 static void ptcache_softbody_interpolate(int index, void *soft_v, void **data, float cfra, float cfra1, float cfra2, float *old_data)
179 {
180         SoftBody *soft= soft_v;
181         BodyPoint *bp = soft->bpoint + index;
182         ParticleKey keys[4];
183         float dfra;
184
185         if(cfra1 == cfra2)
186                 return;
187
188         VECCOPY(keys[1].co, bp->pos);
189         VECCOPY(keys[1].vel, bp->vec);
190
191         if(old_data) {
192                 memcpy(keys[2].co, old_data, 3 * sizeof(float));
193                 memcpy(keys[2].vel, old_data + 3, 3 * sizeof(float));
194         }
195         else
196                 BKE_ptcache_make_particle_key(keys+2, 0, data, cfra2);
197
198         dfra = cfra2 - cfra1;
199
200         mul_v3_fl(keys[1].vel, dfra);
201         mul_v3_fl(keys[2].vel, dfra);
202
203         psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, keys, 1);
204
205         mul_v3_fl(keys->vel, 1.0f / dfra);
206
207         VECCOPY(bp->pos, keys->co);
208         VECCOPY(bp->vec, keys->vel);
209 }
210 static int  ptcache_softbody_totpoint(void *soft_v, int UNUSED(cfra))
211 {
212         SoftBody *soft= soft_v;
213         return soft->totpoint;
214 }
215 /* Particle functions */
216 void BKE_ptcache_make_particle_key(ParticleKey *key, int index, void **data, float time)
217 {
218         PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, index, key->co);
219         PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, index, key->vel);
220         
221         /* no rotation info, so make something nice up */
222         if(data[BPHYS_DATA_ROTATION]==NULL) {
223                 vec_to_quat( key->rot, key->vel, OB_NEGX, OB_POSZ);
224         }
225         else {
226                 PTCACHE_DATA_TO(data, BPHYS_DATA_ROTATION, index, key->rot);
227         }
228
229         PTCACHE_DATA_TO(data, BPHYS_DATA_AVELOCITY, index, key->ave);
230         key->time = time;
231 }
232 static int  ptcache_particle_write(int index, void *psys_v, void **data, int cfra)
233 {
234         ParticleSystem *psys= psys_v;
235         ParticleData *pa = psys->particles + index;
236         BoidParticle *boid = (psys->part->phystype == PART_PHYS_BOIDS) ? pa->boid : NULL;
237         float times[3];
238         int step = psys->pointcache->step;
239
240         /* No need to store unborn or died particles outside cache step bounds */
241         if(data[BPHYS_DATA_INDEX] && (cfra < pa->time - step || cfra > pa->dietime + step))
242                 return 0;
243
244         times[0]= pa->time;
245         times[1]= pa->dietime;
246         times[2]= pa->lifetime;
247
248         PTCACHE_DATA_FROM(data, BPHYS_DATA_INDEX, &index);
249         PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, pa->state.co);
250         PTCACHE_DATA_FROM(data, BPHYS_DATA_VELOCITY, pa->state.vel);
251         PTCACHE_DATA_FROM(data, BPHYS_DATA_ROTATION, pa->state.rot);
252         PTCACHE_DATA_FROM(data, BPHYS_DATA_AVELOCITY, pa->state.ave);
253         PTCACHE_DATA_FROM(data, BPHYS_DATA_SIZE, &pa->size);
254         PTCACHE_DATA_FROM(data, BPHYS_DATA_TIMES, times);
255
256         if(boid)
257                 PTCACHE_DATA_FROM(data, BPHYS_DATA_BOIDS, &boid->data);
258
259         /* return flag 1+1=2 for newly born particles to copy exact birth location to previously cached frame */
260         return 1 + (pa->state.time >= pa->time && pa->prev_state.time <= pa->time);
261 }
262 static void ptcache_particle_read(int index, void *psys_v, void **data, float cfra, float *old_data)
263 {
264         ParticleSystem *psys= psys_v;
265         ParticleData *pa;
266         BoidParticle *boid;
267         float timestep = 0.04f*psys->part->timetweak;
268
269         if(index >= psys->totpart)
270                 return;
271
272         pa = psys->particles + index;
273         boid = (psys->part->phystype == PART_PHYS_BOIDS) ? pa->boid : NULL;
274
275         if(cfra > pa->state.time)
276                 memcpy(&pa->prev_state, &pa->state, sizeof(ParticleKey));
277
278         if(old_data){
279                 /* old format cache */
280                 memcpy(&pa->state, old_data, sizeof(ParticleKey));
281                 return;
282         }
283
284         BKE_ptcache_make_particle_key(&pa->state, 0, data, cfra);
285
286         /* set frames cached before birth to birth time */
287         if(cfra < pa->time)
288                 pa->state.time = pa->time;
289         else if(cfra > pa->dietime)
290                 pa->state.time = pa->dietime;
291
292         if(data[BPHYS_DATA_SIZE])
293                 PTCACHE_DATA_TO(data, BPHYS_DATA_SIZE, 0, &pa->size);
294         
295         if(data[BPHYS_DATA_TIMES]) {
296                 float times[3];
297                 PTCACHE_DATA_TO(data, BPHYS_DATA_TIMES, 0, &times);
298                 pa->time = times[0];
299                 pa->dietime = times[1];
300                 pa->lifetime = times[2];
301         }
302
303         if(boid)
304                 PTCACHE_DATA_TO(data, BPHYS_DATA_BOIDS, 0, &boid->data);
305
306         /* determine velocity from previous location */
307         if(data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_VELOCITY]) {
308                 if(cfra > pa->prev_state.time) {
309                         sub_v3_v3v3(pa->state.vel, pa->state.co, pa->prev_state.co);
310                         mul_v3_fl(pa->state.vel, (cfra - pa->prev_state.time) * timestep);
311                 }
312                 else {
313                         sub_v3_v3v3(pa->state.vel, pa->prev_state.co, pa->state.co);
314                         mul_v3_fl(pa->state.vel, (pa->prev_state.time - cfra) * timestep);
315                 }
316         }
317
318         /* determine rotation from velocity */
319         if(data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_ROTATION]) {
320                 vec_to_quat( pa->state.rot,pa->state.vel, OB_NEGX, OB_POSZ);
321         }
322 }
323 static void ptcache_particle_interpolate(int index, void *psys_v, void **data, float cfra, float cfra1, float cfra2, float *old_data)
324 {
325         ParticleSystem *psys= psys_v;
326         ParticleData *pa;
327         ParticleKey keys[4];
328         float dfra, timestep = 0.04f*psys->part->timetweak;
329
330         if(index >= psys->totpart)
331                 return;
332
333         pa = psys->particles + index;
334
335         /* particle wasn't read from first cache so can't interpolate */
336         if((int)cfra1 < pa->time - psys->pointcache->step || (int)cfra1 > pa->dietime + psys->pointcache->step)
337                 return;
338
339         cfra = MIN2(cfra, pa->dietime);
340         cfra1 = MIN2(cfra1, pa->dietime);
341         cfra2 = MIN2(cfra2, pa->dietime);
342
343         if(cfra1 == cfra2)
344                 return;
345
346         memcpy(keys+1, &pa->state, sizeof(ParticleKey));
347         if(old_data)
348                 memcpy(keys+2, old_data, sizeof(ParticleKey));
349         else
350                 BKE_ptcache_make_particle_key(keys+2, 0, data, cfra2);
351
352         /* determine velocity from previous location */
353         if(data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_VELOCITY]) {
354                 if(keys[1].time > keys[2].time) {
355                         sub_v3_v3v3(keys[2].vel, keys[1].co, keys[2].co);
356                         mul_v3_fl(keys[2].vel, (keys[1].time - keys[2].time) * timestep);
357                 }
358                 else {
359                         sub_v3_v3v3(keys[2].vel, keys[2].co, keys[1].co);
360                         mul_v3_fl(keys[2].vel, (keys[2].time - keys[1].time) * timestep);
361                 }
362         }
363
364         /* determine rotation from velocity */
365         if(data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_ROTATION]) {
366                 vec_to_quat( keys[2].rot,keys[2].vel, OB_NEGX, OB_POSZ);
367         }
368
369         if(cfra > pa->time)
370                 cfra1 = MAX2(cfra1, pa->time);
371
372         dfra = cfra2 - cfra1;
373
374         mul_v3_fl(keys[1].vel, dfra * timestep);
375         mul_v3_fl(keys[2].vel, dfra * timestep);
376
377         psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, &pa->state, 1);
378         interp_qt_qtqt(pa->state.rot, keys[1].rot, keys[2].rot, (cfra - cfra1) / dfra);
379
380         mul_v3_fl(pa->state.vel, 1.f / (dfra * timestep));
381
382         pa->state.time = cfra;
383 }
384
385 static int  ptcache_particle_totpoint(void *psys_v, int UNUSED(cfra))
386 {
387         ParticleSystem *psys = psys_v;
388         return psys->totpart;
389 }
390 static int  ptcache_particle_totwrite(void *psys_v, int cfra)
391 {
392         ParticleSystem *psys = psys_v;
393         ParticleData *pa= psys->particles;
394         int p, step = psys->pointcache->step;
395         int totwrite = 0;
396
397         if(cfra == 0)
398                 return psys->totpart;
399
400         for(p=0; p<psys->totpart; p++,pa++)
401                 totwrite += (cfra >= pa->time - step && cfra <= pa->dietime + step);
402
403         return totwrite;
404 }
405
406 static void ptcache_particle_extra_write(void *psys_v, PTCacheMem *pm, int UNUSED(cfra))
407 {
408         ParticleSystem *psys = psys_v;
409         PTCacheExtra *extra = NULL;
410
411         if(psys->part->phystype == PART_PHYS_FLUID &&
412                 psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS &&
413                 psys->tot_fluidsprings && psys->fluid_springs) {
414
415                 extra = MEM_callocN(sizeof(PTCacheExtra), "Point cache: fluid extra data");
416
417                 extra->type = BPHYS_EXTRA_FLUID_SPRINGS;
418                 extra->totdata = psys->tot_fluidsprings;
419
420                 extra->data = MEM_callocN(extra->totdata * ptcache_extra_datasize[extra->type], "Point cache: extra data");
421                 memcpy(extra->data, psys->fluid_springs, extra->totdata * ptcache_extra_datasize[extra->type]);
422
423                 BLI_addtail(&pm->extradata, extra);
424         }
425 }
426
427 static void ptcache_particle_extra_read(void *psys_v, PTCacheMem *pm, float UNUSED(cfra))
428 {
429         ParticleSystem *psys = psys_v;
430         PTCacheExtra *extra = pm->extradata.first;
431
432         for(; extra; extra=extra->next) {
433                 switch(extra->type) {
434                         case BPHYS_EXTRA_FLUID_SPRINGS:
435                         {
436                                 if(psys->fluid_springs)
437                                         MEM_freeN(psys->fluid_springs);
438
439                                 psys->fluid_springs = MEM_dupallocN(extra->data);
440                                 psys->tot_fluidsprings = psys->alloc_fluidsprings = extra->totdata;
441                                 break;
442                         }
443                 }
444         }
445 }
446
447 /* Cloth functions */
448 static int  ptcache_cloth_write(int index, void *cloth_v, void **data, int UNUSED(cfra))
449 {
450         ClothModifierData *clmd= cloth_v;
451         Cloth *cloth= clmd->clothObject;
452         ClothVertex *vert = cloth->verts + index;
453
454         PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, vert->x);
455         PTCACHE_DATA_FROM(data, BPHYS_DATA_VELOCITY, vert->v);
456         PTCACHE_DATA_FROM(data, BPHYS_DATA_XCONST, vert->xconst);
457
458         return 1;
459 }
460 static void ptcache_cloth_read(int index, void *cloth_v, void **data, float UNUSED(cfra), float *old_data)
461 {
462         ClothModifierData *clmd= cloth_v;
463         Cloth *cloth= clmd->clothObject;
464         ClothVertex *vert = cloth->verts + index;
465         
466         if(old_data) {
467                 memcpy(vert->x, data, 3 * sizeof(float));
468                 memcpy(vert->xconst, data + 3, 3 * sizeof(float));
469                 memcpy(vert->v, data + 6, 3 * sizeof(float));
470         }
471         else {
472                 PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, 0, vert->x);
473                 PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, 0, vert->v);
474                 PTCACHE_DATA_TO(data, BPHYS_DATA_XCONST, 0, vert->xconst);
475         }
476 }
477 static void ptcache_cloth_interpolate(int index, void *cloth_v, void **data, float cfra, float cfra1, float cfra2, float *old_data)
478 {
479         ClothModifierData *clmd= cloth_v;
480         Cloth *cloth= clmd->clothObject;
481         ClothVertex *vert = cloth->verts + index;
482         ParticleKey keys[4];
483         float dfra;
484
485         if(cfra1 == cfra2)
486                 return;
487
488         VECCOPY(keys[1].co, vert->x);
489         VECCOPY(keys[1].vel, vert->v);
490
491         if(old_data) {
492                 memcpy(keys[2].co, old_data, 3 * sizeof(float));
493                 memcpy(keys[2].vel, old_data + 6, 3 * sizeof(float));
494         }
495         else
496                 BKE_ptcache_make_particle_key(keys+2, 0, data, cfra2);
497
498         dfra = cfra2 - cfra1;
499
500         mul_v3_fl(keys[1].vel, dfra);
501         mul_v3_fl(keys[2].vel, dfra);
502
503         psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, keys, 1);
504
505         mul_v3_fl(keys->vel, 1.0f / dfra);
506
507         VECCOPY(vert->x, keys->co);
508         VECCOPY(vert->v, keys->vel);
509
510         /* should vert->xconst be interpolated somehow too? - jahka */
511 }
512
513 static int  ptcache_cloth_totpoint(void *cloth_v, int UNUSED(cfra))
514 {
515         ClothModifierData *clmd= cloth_v;
516         return clmd->clothObject ? clmd->clothObject->numverts : 0;
517 }
518
519 /* Smoke functions */
520 static int  ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra))
521 {
522         SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
523         SmokeDomainSettings *sds = smd->domain;
524         
525         if(sds->fluid) {
526                 return sds->res[0]*sds->res[1]*sds->res[2];
527         }
528         else
529                 return 0;
530 }
531 static int  ptcache_smoke_write(PTCacheFile *pf, void *smoke_v)
532 {       
533         SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
534         SmokeDomainSettings *sds = smd->domain;
535         int ret = 0;
536         
537         if(sds->fluid) {
538                 size_t res = sds->res[0]*sds->res[1]*sds->res[2];
539                 float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold;
540                 unsigned char *obstacles;
541                 unsigned int in_len = sizeof(float)*(unsigned int)res;
542                 unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
543                 //int mode = res >= 1000000 ? 2 : 1;
544                 int mode=1;             // light
545                 if (sds->cache_comp == SM_CACHE_HEAVY) mode=2;  // heavy
546
547                 smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles);
548
549                 ptcache_file_compressed_write(pf, (unsigned char *)sds->shadow, in_len, out, mode);
550                 ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len, out, mode);
551                 ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len, out, mode); 
552                 ptcache_file_compressed_write(pf, (unsigned char *)heat, in_len, out, mode);
553                 ptcache_file_compressed_write(pf, (unsigned char *)heatold, in_len, out, mode);
554                 ptcache_file_compressed_write(pf, (unsigned char *)vx, in_len, out, mode);
555                 ptcache_file_compressed_write(pf, (unsigned char *)vy, in_len, out, mode);
556                 ptcache_file_compressed_write(pf, (unsigned char *)vz, in_len, out, mode);
557                 ptcache_file_compressed_write(pf, (unsigned char *)vxold, in_len, out, mode);
558                 ptcache_file_compressed_write(pf, (unsigned char *)vyold, in_len, out, mode);
559                 ptcache_file_compressed_write(pf, (unsigned char *)vzold, in_len, out, mode);
560                 ptcache_file_compressed_write(pf, (unsigned char *)obstacles, (unsigned int)res, out, mode);
561                 ptcache_file_write(pf, &dt, 1, sizeof(float));
562                 ptcache_file_write(pf, &dx, 1, sizeof(float));
563
564                 MEM_freeN(out);
565                 
566                 ret = 1;
567         }
568
569         if(sds->wt) {
570                 int res_big_array[3];
571                 int res_big;
572                 int res = sds->res[0]*sds->res[1]*sds->res[2];
573                 float *dens, *densold, *tcu, *tcv, *tcw;
574                 unsigned int in_len = sizeof(float)*(unsigned int)res;
575                 unsigned int in_len_big;
576                 unsigned char *out;
577                 int mode;
578
579                 smoke_turbulence_get_res(sds->wt, res_big_array);
580                 res_big = res_big_array[0]*res_big_array[1]*res_big_array[2];
581                 //mode =  res_big >= 1000000 ? 2 : 1;
582                 mode = 1;       // light
583                 if (sds->cache_high_comp == SM_CACHE_HEAVY) mode=2;     // heavy
584
585                 in_len_big = sizeof(float) * (unsigned int)res_big;
586
587                 smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw);
588
589                 out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len_big), "pointcache_lzo_buffer");
590                 ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len_big, out, mode);
591                 ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len_big, out, mode);     
592                 MEM_freeN(out);
593
594                 out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len), "pointcache_lzo_buffer");
595                 ptcache_file_compressed_write(pf, (unsigned char *)tcu, in_len, out, mode);
596                 ptcache_file_compressed_write(pf, (unsigned char *)tcv, in_len, out, mode);
597                 ptcache_file_compressed_write(pf, (unsigned char *)tcw, in_len, out, mode);
598                 MEM_freeN(out);
599                 
600                 ret = 1;
601         }
602
603         return ret;
604 }
605 static void ptcache_smoke_read(PTCacheFile *pf, void *smoke_v)
606 {
607         SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
608         SmokeDomainSettings *sds = smd->domain;
609         
610         if(sds->fluid) {
611                 size_t res = sds->res[0]*sds->res[1]*sds->res[2];
612                 float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold;
613                 unsigned char *obstacles;
614                 unsigned int out_len = (unsigned int)res * sizeof(float);
615                 
616                 smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles);
617
618                 ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len);
619                 ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len);
620                 ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len);
621                 ptcache_file_compressed_read(pf, (unsigned char*)heat, out_len);
622                 ptcache_file_compressed_read(pf, (unsigned char*)heatold, out_len);
623                 ptcache_file_compressed_read(pf, (unsigned char*)vx, out_len);
624                 ptcache_file_compressed_read(pf, (unsigned char*)vy, out_len);
625                 ptcache_file_compressed_read(pf, (unsigned char*)vz, out_len);
626                 ptcache_file_compressed_read(pf, (unsigned char*)vxold, out_len);
627                 ptcache_file_compressed_read(pf, (unsigned char*)vyold, out_len);
628                 ptcache_file_compressed_read(pf, (unsigned char*)vzold, out_len);
629                 ptcache_file_compressed_read(pf, (unsigned char*)obstacles, (unsigned int)res);
630                 ptcache_file_read(pf, &dt, 1, sizeof(float));
631                 ptcache_file_read(pf, &dx, 1, sizeof(float));
632
633                 if(pf->data_types & (1<<BPHYS_DATA_SMOKE_HIGH) && sds->wt) {
634                         int res = sds->res[0]*sds->res[1]*sds->res[2];
635                         int res_big, res_big_array[3];
636                         float *dens, *densold, *tcu, *tcv, *tcw;
637                         unsigned int out_len = sizeof(float)*(unsigned int)res;
638                         unsigned int out_len_big;
639
640                         smoke_turbulence_get_res(sds->wt, res_big_array);
641                         res_big = res_big_array[0]*res_big_array[1]*res_big_array[2];
642                         out_len_big = sizeof(float) * (unsigned int)res_big;
643
644                         smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw);
645
646                         ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len_big);
647                         ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len_big);
648
649                         ptcache_file_compressed_read(pf, (unsigned char*)tcu, out_len);
650                         ptcache_file_compressed_read(pf, (unsigned char*)tcv, out_len);
651                         ptcache_file_compressed_read(pf, (unsigned char*)tcw, out_len);
652                 }
653         }
654 }
655
656 /* Creating ID's */
657 void BKE_ptcache_id_from_softbody(PTCacheID *pid, Object *ob, SoftBody *sb)
658 {
659         memset(pid, 0, sizeof(PTCacheID));
660
661         pid->ob= ob;
662         pid->calldata= sb;
663         pid->type= PTCACHE_TYPE_SOFTBODY;
664         pid->cache= sb->pointcache;
665         pid->cache_ptr= &sb->pointcache;
666         pid->ptcaches= &sb->ptcaches;
667         pid->totpoint= pid->totwrite= ptcache_softbody_totpoint;
668
669         pid->write_point                        = ptcache_softbody_write;
670         pid->read_point                         = ptcache_softbody_read;
671         pid->interpolate_point          = ptcache_softbody_interpolate;
672
673         pid->write_stream                       = NULL;
674         pid->read_stream                        = NULL;
675
676         pid->write_extra_data           = NULL;
677         pid->read_extra_data            = NULL;
678         pid->interpolate_extra_data     = NULL;
679
680         pid->write_header                       = ptcache_basic_header_write;
681         pid->read_header                        = ptcache_basic_header_read;
682
683         pid->data_types= (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY);
684         pid->info_types= 0;
685
686         pid->stack_index = pid->cache->index;
687 }
688 void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *psys)
689 {
690         memset(pid, 0, sizeof(PTCacheID));
691
692         pid->ob= ob;
693         pid->calldata= psys;
694         pid->type= PTCACHE_TYPE_PARTICLES;
695         pid->stack_index= psys->pointcache->index;
696         pid->cache= psys->pointcache;
697         pid->cache_ptr= &psys->pointcache;
698         pid->ptcaches= &psys->ptcaches;
699
700         if(psys->part->type != PART_HAIR)
701                 pid->flag |= PTCACHE_VEL_PER_SEC;
702
703         pid->totpoint                           = ptcache_particle_totpoint;
704         pid->totwrite                           = ptcache_particle_totwrite;
705
706         pid->write_point                                = ptcache_particle_write;
707         pid->read_point                         = ptcache_particle_read;
708         pid->interpolate_point          = ptcache_particle_interpolate;
709
710         pid->write_stream                       = NULL;
711         pid->read_stream                        = NULL;
712
713         pid->write_extra_data           = NULL;
714         pid->read_extra_data            = NULL;
715         pid->interpolate_extra_data     = NULL;
716
717         pid->write_header                       = ptcache_basic_header_write;
718         pid->read_header                        = ptcache_basic_header_read;
719
720         pid->data_types = (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY) | (1<<BPHYS_DATA_INDEX);
721
722         if(psys->part->phystype == PART_PHYS_BOIDS)
723                 pid->data_types|= (1<<BPHYS_DATA_AVELOCITY) | (1<<BPHYS_DATA_ROTATION) | (1<<BPHYS_DATA_BOIDS);
724         else if(psys->part->phystype == PART_PHYS_FLUID && psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS) {
725                 pid->write_extra_data = ptcache_particle_extra_write;
726                 pid->read_extra_data = ptcache_particle_extra_read;
727         }
728
729         if(psys->part->rotmode!=PART_ROT_VEL
730                 || psys->part->avemode!=PART_AVE_SPIN || psys->part->avefac!=0.0f)
731                 pid->data_types|= (1<<BPHYS_DATA_AVELOCITY) | (1<<BPHYS_DATA_ROTATION);
732
733         if(psys->part->flag & PART_ROT_DYN)
734                 pid->data_types|= (1<<BPHYS_DATA_ROTATION);
735
736         pid->info_types= (1<<BPHYS_DATA_TIMES);
737 }
738 void BKE_ptcache_id_from_cloth(PTCacheID *pid, Object *ob, ClothModifierData *clmd)
739 {
740         memset(pid, 0, sizeof(PTCacheID));
741
742         pid->ob= ob;
743         pid->calldata= clmd;
744         pid->type= PTCACHE_TYPE_CLOTH;
745         pid->stack_index= clmd->point_cache->index;
746         pid->cache= clmd->point_cache;
747         pid->cache_ptr= &clmd->point_cache;
748         pid->ptcaches= &clmd->ptcaches;
749         pid->totpoint= pid->totwrite= ptcache_cloth_totpoint;
750
751         pid->write_point                        = ptcache_cloth_write;
752         pid->read_point                         = ptcache_cloth_read;
753         pid->interpolate_point          = ptcache_cloth_interpolate;
754
755         pid->write_stream                       = NULL;
756         pid->read_stream                        = NULL;
757
758         pid->write_extra_data           = NULL;
759         pid->read_extra_data            = NULL;
760         pid->interpolate_extra_data     = NULL;
761
762         pid->write_header                       = ptcache_basic_header_write;
763         pid->read_header                        = ptcache_basic_header_read;
764
765         pid->data_types= (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY) | (1<<BPHYS_DATA_XCONST);
766         pid->info_types= 0;
767 }
768 void BKE_ptcache_id_from_smoke(PTCacheID *pid, struct Object *ob, struct SmokeModifierData *smd)
769 {
770         SmokeDomainSettings *sds = smd->domain;
771
772         memset(pid, 0, sizeof(PTCacheID));
773
774         pid->ob= ob;
775         pid->calldata= smd;
776         
777         pid->type= PTCACHE_TYPE_SMOKE_DOMAIN;
778         pid->stack_index= sds->point_cache[0]->index;
779
780         pid->cache= sds->point_cache[0];
781         pid->cache_ptr= &(sds->point_cache[0]);
782         pid->ptcaches= &(sds->ptcaches[0]);
783
784         pid->totpoint= pid->totwrite= ptcache_smoke_totpoint;
785
786         pid->write_point                        = NULL;
787         pid->read_point                         = NULL;
788         pid->interpolate_point          = NULL;
789
790         pid->read_stream                        = ptcache_smoke_read;
791         pid->write_stream                       = ptcache_smoke_write;
792
793         pid->write_extra_data           = NULL;
794         pid->read_extra_data            = NULL;
795         pid->interpolate_extra_data     = NULL;
796
797         pid->write_header                       = ptcache_basic_header_write;
798         pid->read_header                        = ptcache_basic_header_read;
799
800         pid->data_types= 0;
801         pid->info_types= 0;
802
803         if(sds->fluid)
804                 pid->data_types |= (1<<BPHYS_DATA_SMOKE_LOW);
805         if(sds->wt)
806                 pid->data_types |= (1<<BPHYS_DATA_SMOKE_HIGH);
807 }
808 void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int duplis)
809 {
810         PTCacheID *pid;
811         ParticleSystem *psys;
812         ModifierData *md;
813
814         lb->first= lb->last= NULL;
815
816         if(ob->soft) {
817                 pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
818                 BKE_ptcache_id_from_softbody(pid, ob, ob->soft);
819                 BLI_addtail(lb, pid);
820         }
821
822         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
823                 if(psys->part==NULL)
824                         continue;
825                 
826                 /* check to make sure point cache is actually used by the particles */
827                 if(ELEM(psys->part->phystype, PART_PHYS_NO, PART_PHYS_KEYED))
828                         continue;
829
830                 /* hair needs to be included in id-list for cache edit mode to work */
831                 /* if(psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DYNAMICS)==0) */
832                 /*      continue; */
833                         
834                 if(psys->part->type == PART_FLUID)
835                         continue;
836
837                 pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
838                 BKE_ptcache_id_from_particles(pid, ob, psys);
839                 BLI_addtail(lb, pid);
840         }
841
842         for(md=ob->modifiers.first; md; md=md->next) {
843                 if(md->type == eModifierType_Cloth) {
844                         pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
845                         BKE_ptcache_id_from_cloth(pid, ob, (ClothModifierData*)md);
846                         BLI_addtail(lb, pid);
847                 }
848                 if(md->type == eModifierType_Smoke) {
849                         SmokeModifierData *smd = (SmokeModifierData *)md;
850                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
851                         {
852                                 pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
853                                 BKE_ptcache_id_from_smoke(pid, ob, (SmokeModifierData*)md);
854                                 BLI_addtail(lb, pid);
855                         }
856                 }
857         }
858
859         if(scene && (duplis-- > 0) && (ob->transflag & OB_DUPLI)) {
860                 ListBase *lb_dupli_ob;
861
862                 if((lb_dupli_ob=object_duplilist(scene, ob))) {
863                         DupliObject *dob;
864                         for(dob= lb_dupli_ob->first; dob; dob= dob->next) {
865                                 if(dob->ob != ob) { /* avoids recursive loops with dupliframes: bug 22988 */
866                                         ListBase lb_dupli_pid;
867                                         BKE_ptcache_ids_from_object(&lb_dupli_pid, dob->ob, scene, duplis);
868                                         BLI_movelisttolist(lb, &lb_dupli_pid);
869                                         if(lb_dupli_pid.first)
870                                                 printf("Adding Dupli\n");
871                                 }
872                         }
873
874                         free_object_duplilist(lb_dupli_ob);     /* does restore */
875                 }
876         }
877 }
878
879 /* File handling */
880
881 /*      Takes an Object ID and returns a unique name
882         - id: object id
883         - cfra: frame for the cache, can be negative
884         - stack_index: index in the modifier stack. we can have cache for more then one stack_index
885 */
886
887 #define MAX_PTCACHE_PATH FILE_MAX
888 #define MAX_PTCACHE_FILE ((FILE_MAXDIR+FILE_MAXFILE)*2)
889
890 static int ptcache_path(PTCacheID *pid, char *filename)
891 {
892         Library *lib= (pid->ob)? pid->ob->id.lib: NULL;
893         const char *blendfilename= (lib && (pid->cache->flag & PTCACHE_IGNORE_LIBPATH)==0) ? lib->filepath: G.main->name;
894         size_t i;
895
896         if(pid->cache->flag & PTCACHE_EXTERNAL) {
897                 strcpy(filename, pid->cache->path);
898
899                 if(strncmp(filename, "//", 2)==0)
900                         BLI_path_abs(filename, blendfilename);
901
902                 return BLI_add_slash(filename); /* new strlen() */
903         }
904         else if (G.relbase_valid || lib) {
905                 char file[MAX_PTCACHE_PATH]; /* we dont want the dir, only the file */
906
907                 BLI_split_dirfile(blendfilename, NULL, file);
908                 i = strlen(file);
909                 
910                 /* remove .blend */
911                 if (i > 6)
912                         file[i-6] = '\0';
913                 
914                 snprintf(filename, MAX_PTCACHE_PATH, "//"PTCACHE_PATH"%s", file); /* add blend file name to pointcache dir */
915                 BLI_path_abs(filename, blendfilename);
916                 return BLI_add_slash(filename); /* new strlen() */
917         }
918         
919         /* use the temp path. this is weak but better then not using point cache at all */
920         /* btempdir is assumed to exist and ALWAYS has a trailing slash */
921         snprintf(filename, MAX_PTCACHE_PATH, "%s"PTCACHE_PATH"%d", btempdir, abs(getpid()));
922         
923         return BLI_add_slash(filename); /* new strlen() */
924 }
925
926 static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_path, short do_ext)
927 {
928         int len=0;
929         char *idname;
930         char *newname;
931         filename[0] = '\0';
932         newname = filename;
933         
934         if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return 0; /* save blend file before using disk pointcache */
935         
936         /* start with temp dir */
937         if (do_path) {
938                 len = ptcache_path(pid, filename);
939                 newname += len;
940         }
941         if(strcmp(pid->cache->name, "")==0 && (pid->cache->flag & PTCACHE_EXTERNAL)==0) {
942                 idname = (pid->ob->id.name+2);
943                 /* convert chars to hex so they are always a valid filename */
944                 while('\0' != *idname) {
945                         snprintf(newname, MAX_PTCACHE_FILE, "%02X", (char)(*idname++));
946                         newname+=2;
947                         len += 2;
948                 }
949         }
950         else {
951                 int temp = (int)strlen(pid->cache->name); 
952                 strcpy(newname, pid->cache->name); 
953                 newname+=temp;
954                 len += temp;
955         }
956
957         if (do_ext) {
958
959                 if(pid->cache->index < 0)
960                         pid->cache->index =  pid->stack_index = object_insert_ptcache(pid->ob);
961
962                 if(pid->cache->flag & PTCACHE_EXTERNAL) {
963                         if(pid->cache->index >= 0)
964                                 snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02d"PTCACHE_EXT, cfra, pid->stack_index); /* always 6 chars */
965                         else
966                                 snprintf(newname, MAX_PTCACHE_FILE, "_%06d"PTCACHE_EXT, cfra); /* always 6 chars */
967                 }
968                 else {
969                         snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02d"PTCACHE_EXT, cfra, pid->stack_index); /* always 6 chars */
970                 }
971                 len += 16;
972         }
973         
974         return len; /* make sure the above string is always 16 chars */
975 }
976
977 /* youll need to close yourself after! */
978 static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra)
979 {
980         PTCacheFile *pf;
981         FILE *fp = NULL;
982         char filename[(FILE_MAXDIR+FILE_MAXFILE)*2];
983
984 #ifndef DURIAN_POINTCACHE_LIB_OK
985         /* don't allow writing for linked objects */
986         if(pid->ob->id.lib && mode == PTCACHE_FILE_WRITE)
987                 return NULL;
988 #endif
989         if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return NULL; /* save blend file before using disk pointcache */
990         
991         ptcache_filename(pid, filename, cfra, 1, 1);
992
993         if (mode==PTCACHE_FILE_READ) {
994                 if (!BLI_exists(filename)) {
995                         return NULL;
996                 }
997                  fp = fopen(filename, "rb");
998         } else if (mode==PTCACHE_FILE_WRITE) {
999                 BLI_make_existing_file(filename); /* will create the dir if needs be, same as //textures is created */
1000                 fp = fopen(filename, "wb");
1001         } else if (mode==PTCACHE_FILE_UPDATE) {
1002                 BLI_make_existing_file(filename);
1003                 fp = fopen(filename, "rb+");
1004         }
1005
1006         if (!fp)
1007                 return NULL;
1008
1009         pf= MEM_mallocN(sizeof(PTCacheFile), "PTCacheFile");
1010         pf->fp= fp;
1011         pf->old_format = 0;
1012         pf->frame = cfra;
1013
1014         return pf;
1015 }
1016 static void ptcache_file_close(PTCacheFile *pf)
1017 {
1018         if(pf) {
1019                 fclose(pf->fp);
1020                 MEM_freeN(pf);
1021         }
1022 }
1023
1024 static int ptcache_file_compressed_read(PTCacheFile *pf, unsigned char *result, unsigned int len)
1025 {
1026         int r = 0;
1027         unsigned char compressed = 0;
1028         size_t in_len;
1029 #ifdef WITH_LZO
1030         size_t out_len = len;
1031 #endif
1032         unsigned char *in;
1033         unsigned char *props = MEM_callocN(16*sizeof(char), "tmp");
1034
1035         ptcache_file_read(pf, &compressed, 1, sizeof(unsigned char));
1036         if(compressed) {
1037                 unsigned int size;
1038                 ptcache_file_read(pf, &size, 1, sizeof(unsigned int));
1039                 in_len = (size_t)size;
1040                 if(in_len==0) {
1041                         /* do nothing */
1042                 }
1043                 else {
1044                         in = (unsigned char *)MEM_callocN(sizeof(unsigned char)*in_len, "pointcache_compressed_buffer");
1045                         ptcache_file_read(pf, in, in_len, sizeof(unsigned char));
1046 #ifdef WITH_LZO
1047                         if(compressed == 1)
1048                                 r = lzo1x_decompress_safe(in, (lzo_uint)in_len, result, (lzo_uint *)&out_len, NULL);
1049 #endif
1050 #ifdef WITH_LZMA
1051                         if(compressed == 2)
1052                         {
1053                                 size_t sizeOfIt;
1054                                 size_t leni = in_len, leno = out_len;
1055                                 ptcache_file_read(pf, &size, 1, sizeof(unsigned int));
1056                                 sizeOfIt = (size_t)size;
1057                                 ptcache_file_read(pf, props, sizeOfIt, sizeof(unsigned char));
1058                                 r = LzmaUncompress(result, &leno, in, &leni, props, sizeOfIt);
1059                         }
1060 #endif
1061                         MEM_freeN(in);
1062                 }
1063         }
1064         else {
1065                 ptcache_file_read(pf, result, len, sizeof(unsigned char));
1066         }
1067
1068         MEM_freeN(props);
1069
1070         return r;
1071 }
1072 static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, unsigned int in_len, unsigned char *out, int mode)
1073 {
1074         int r = 0;
1075         unsigned char compressed = 0;
1076         size_t out_len= 0;
1077         unsigned char *props = MEM_callocN(16*sizeof(char), "tmp");
1078         size_t sizeOfIt = 5;
1079
1080         (void)mode; /* unused when building w/o compression */
1081
1082 #ifdef WITH_LZO
1083         out_len= LZO_OUT_LEN(in_len);
1084         if(mode == 1) {
1085                 LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS);
1086                 
1087                 r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem);  
1088                 if (!(r == LZO_E_OK) || (out_len >= in_len))
1089                         compressed = 0;
1090                 else
1091                         compressed = 1;
1092         }
1093 #endif
1094 #ifdef WITH_LZMA
1095         if(mode == 2) {
1096                 
1097                 r = LzmaCompress(out, &out_len, in, in_len,//assume sizeof(char)==1....
1098                                                 props, &sizeOfIt, 5, 1 << 24, 3, 0, 2, 32, 2);
1099
1100                 if(!(r == SZ_OK) || (out_len >= in_len))
1101                         compressed = 0;
1102                 else
1103                         compressed = 2;
1104         }
1105 #endif
1106         
1107         ptcache_file_write(pf, &compressed, 1, sizeof(unsigned char));
1108         if(compressed) {
1109                 unsigned int size = out_len;
1110                 ptcache_file_write(pf, &size, 1, sizeof(unsigned int));
1111                 ptcache_file_write(pf, out, out_len, sizeof(unsigned char));
1112         }
1113         else
1114                 ptcache_file_write(pf, in, in_len, sizeof(unsigned char));
1115
1116         if(compressed == 2)
1117         {
1118                 unsigned int size = sizeOfIt;
1119                 ptcache_file_write(pf, &sizeOfIt, 1, sizeof(unsigned int));
1120                 ptcache_file_write(pf, props, size, sizeof(unsigned char));
1121         }
1122
1123         MEM_freeN(props);
1124
1125         return r;
1126 }
1127 static int ptcache_file_read(PTCacheFile *pf, void *f, unsigned int tot, unsigned int size)
1128 {
1129         return (fread(f, size, tot, pf->fp) == tot);
1130 }
1131 static int ptcache_file_write(PTCacheFile *pf, void *f, unsigned int tot, unsigned int size)
1132 {
1133         return (fwrite(f, size, tot, pf->fp) == tot);
1134 }
1135 static int ptcache_file_data_read(PTCacheFile *pf)
1136 {
1137         int i;
1138
1139         for(i=0; i<BPHYS_TOT_DATA; i++) {
1140                 if((pf->data_types & (1<<i)) && !ptcache_file_read(pf, pf->cur[i], 1, ptcache_data_size[i]))
1141                         return 0;
1142         }
1143         
1144         return 1;
1145 }
1146 static int ptcache_file_data_write(PTCacheFile *pf)
1147 {               
1148         int i;
1149
1150         for(i=0; i<BPHYS_TOT_DATA; i++) {
1151                 if((pf->data_types & (1<<i)) && !ptcache_file_write(pf, pf->cur[i], 1, ptcache_data_size[i]))
1152                         return 0;
1153         }
1154         
1155         return 1;
1156 }
1157 static int ptcache_file_header_begin_read(PTCacheFile *pf)
1158 {
1159         unsigned int typeflag=0;
1160         int error=0;
1161         char bphysics[8];
1162         
1163         pf->data_types = 0;
1164         
1165         if(fread(bphysics, sizeof(char), 8, pf->fp) != 8)
1166                 error = 1;
1167         
1168         if(!error && strncmp(bphysics, "BPHYSICS", 8))
1169                 error = 1;
1170
1171         if(!error && !fread(&typeflag, sizeof(unsigned int), 1, pf->fp))
1172                 error = 1;
1173
1174         pf->type = (typeflag & PTCACHE_TYPEFLAG_TYPEMASK);
1175         pf->flag = (typeflag & PTCACHE_TYPEFLAG_FLAGMASK);
1176         
1177         /* if there was an error set file as it was */
1178         if(error)
1179                 fseek(pf->fp, 0, SEEK_SET);
1180
1181         return !error;
1182 }
1183 static int ptcache_file_header_begin_write(PTCacheFile *pf)
1184 {
1185         const char *bphysics = "BPHYSICS";
1186         unsigned int typeflag = pf->type + pf->flag;
1187         
1188         if(fwrite(bphysics, sizeof(char), 8, pf->fp) != 8)
1189                 return 0;
1190
1191         if(!fwrite(&typeflag, sizeof(unsigned int), 1, pf->fp))
1192                 return 0;
1193         
1194         return 1;
1195 }
1196
1197 /* Data pointer handling */
1198 int BKE_ptcache_data_size(int data_type)
1199 {
1200         return ptcache_data_size[data_type];
1201 }
1202
1203 static void ptcache_file_pointers_init(PTCacheFile *pf)
1204 {
1205         int data_types = pf->data_types;
1206
1207         pf->cur[BPHYS_DATA_INDEX] =             (data_types & (1<<BPHYS_DATA_INDEX))    ?               &pf->data.index : NULL;
1208         pf->cur[BPHYS_DATA_LOCATION] =  (data_types & (1<<BPHYS_DATA_LOCATION)) ?               &pf->data.loc   : NULL;
1209         pf->cur[BPHYS_DATA_VELOCITY] =  (data_types & (1<<BPHYS_DATA_VELOCITY)) ?               &pf->data.vel   : NULL;
1210         pf->cur[BPHYS_DATA_ROTATION] =  (data_types & (1<<BPHYS_DATA_ROTATION)) ?               &pf->data.rot   : NULL;
1211         pf->cur[BPHYS_DATA_AVELOCITY] = (data_types & (1<<BPHYS_DATA_AVELOCITY))?               &pf->data.ave   : NULL;
1212         pf->cur[BPHYS_DATA_SIZE] =              (data_types & (1<<BPHYS_DATA_SIZE))             ?               &pf->data.size  : NULL;
1213         pf->cur[BPHYS_DATA_TIMES] =             (data_types & (1<<BPHYS_DATA_TIMES))    ?               &pf->data.times : NULL;
1214         pf->cur[BPHYS_DATA_BOIDS] =             (data_types & (1<<BPHYS_DATA_BOIDS))    ?               &pf->data.boids : NULL;
1215 }
1216
1217 /* Check to see if point number "index" is in pm, uses binary search for index data. */
1218 int BKE_ptcache_mem_index_find(PTCacheMem *pm, unsigned int index)
1219 {
1220         if(pm->data[BPHYS_DATA_INDEX]) {
1221                 unsigned int *data = pm->data[BPHYS_DATA_INDEX];
1222                 unsigned int mid, low = 0, high = pm->totpoint - 1;
1223
1224                 if(index < *data || index > *(data+high))
1225                         return -1;
1226
1227                 /* check simple case for continuous indexes first */
1228                 if(index-*data < high && data[index-*data] == index)
1229                         return index-*data;
1230
1231                 while(low <= high) {
1232                         mid= (low + high)/2;
1233
1234                         if(data[mid] > index)
1235                                 high = mid - 1;
1236                         else if(data[mid] < index)
1237                                 low = mid + 1;
1238                         else
1239                                 return mid;
1240                 }
1241
1242                 return -1;
1243         }
1244         else {
1245                 return (index < pm->totpoint ? index : -1);
1246         }
1247 }
1248
1249 void BKE_ptcache_mem_pointers_init(PTCacheMem *pm)
1250 {
1251         int data_types = pm->data_types;
1252         int i;
1253
1254         for(i=0; i<BPHYS_TOT_DATA; i++)
1255                 pm->cur[i] = ((data_types & (1<<i)) ? pm->data[i] : NULL);
1256 }
1257
1258 void BKE_ptcache_mem_pointers_incr(PTCacheMem *pm)
1259 {
1260         int i;
1261
1262         for(i=0; i<BPHYS_TOT_DATA; i++) {
1263                 if(pm->cur[i])
1264                         pm->cur[i] = (char*)pm->cur[i] + ptcache_data_size[i];
1265         }
1266 }
1267 int  BKE_ptcache_mem_pointers_seek(int point_index, PTCacheMem *pm)
1268 {
1269         int data_types = pm->data_types;
1270         int i, index = BKE_ptcache_mem_index_find(pm, point_index);
1271
1272         if(index < 0) {
1273                 /* Can't give proper location without reallocation, so don't give any location.
1274                  * Some points will be cached improperly, but this only happens with simulation
1275                  * steps bigger than cache->step, so the cache has to be recalculated anyways
1276                  * at some point.
1277                  */
1278                 return 0;
1279         }
1280
1281         for(i=0; i<BPHYS_TOT_DATA; i++)
1282                 pm->cur[i] = data_types & (1<<i) ? (char*)pm->data[i] + index * ptcache_data_size[i] : NULL;
1283
1284         return 1;
1285 }
1286 static void ptcache_data_alloc(PTCacheMem *pm)
1287 {
1288         int data_types = pm->data_types;
1289         int totpoint = pm->totpoint;
1290         int i;
1291
1292         for(i=0; i<BPHYS_TOT_DATA; i++) {
1293                 if(data_types & (1<<i))
1294                         pm->data[i] = MEM_callocN(totpoint * ptcache_data_size[i], "PTCache Data");
1295         }
1296 }
1297 static void ptcache_data_free(PTCacheMem *pm)
1298 {
1299         void **data = pm->data;
1300         int i;
1301
1302         for(i=0; i<BPHYS_TOT_DATA; i++) {
1303                 if(data[i])
1304                         MEM_freeN(data[i]);
1305         }
1306 }
1307 static void ptcache_data_copy(void *from[], void *to[])
1308 {
1309         int i;
1310         for(i=0; i<BPHYS_TOT_DATA; i++) {
1311         /* note, durian file 03.4b_comp crashes if to[i] is not tested
1312          * its NULL, not sure if this should be fixed elsewhere but for now its needed */
1313                 if(from[i] && to[i])
1314                         memcpy(to[i], from[i], ptcache_data_size[i]);
1315         }
1316 }
1317
1318 static void ptcache_extra_free(PTCacheMem *pm)
1319 {
1320         PTCacheExtra *extra = pm->extradata.first;
1321
1322         if(extra) {
1323                 for(; extra; extra=extra->next) {
1324                         if(extra->data)
1325                                 MEM_freeN(extra->data);
1326                 }
1327
1328                 BLI_freelistN(&pm->extradata);
1329         }
1330 }
1331 static int ptcache_old_elemsize(PTCacheID *pid)
1332 {
1333         if(pid->type==PTCACHE_TYPE_SOFTBODY)
1334                 return 6 * sizeof(float);
1335         else if(pid->type==PTCACHE_TYPE_PARTICLES)
1336                 return sizeof(ParticleKey);
1337         else if(pid->type==PTCACHE_TYPE_CLOTH)
1338                 return 9 * sizeof(float);
1339
1340         return 0;
1341 }
1342
1343 static void ptcache_find_frames_around(PTCacheID *pid, unsigned int frame, int *fra1, int *fra2)
1344 {
1345         if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1346                 int cfra1=frame-1, cfra2=frame+1;
1347
1348                 while(cfra1 >= pid->cache->startframe && !BKE_ptcache_id_exist(pid, cfra1))
1349                         cfra1--;
1350
1351                 if(cfra1 < pid->cache->startframe)
1352                         cfra1 = 0;
1353
1354                 while(cfra2 <= pid->cache->endframe && !BKE_ptcache_id_exist(pid, cfra2))
1355                         cfra2++;
1356
1357                 if(cfra2 > pid->cache->endframe)
1358                         cfra2 = 0;
1359
1360                 if(cfra1 && !cfra2) {
1361                         *fra1 = 0;
1362                         *fra2 = cfra1;
1363                 }
1364                 else {
1365                         *fra1 = cfra1;
1366                         *fra2 = cfra2;
1367                 }
1368         }
1369         else if(pid->cache->mem_cache.first) {
1370                 PTCacheMem *pm = pid->cache->mem_cache.first;
1371                 PTCacheMem *pm2 = pid->cache->mem_cache.last;
1372
1373                 while(pm->next && pm->next->frame < frame)
1374                         pm= pm->next;
1375
1376                 if(pm2->frame < frame) {
1377                         pm2 = NULL;
1378                 }
1379                 else {
1380                         while(pm2->prev && pm2->prev->frame > frame) {
1381                                 pm2= pm2->prev;
1382                         }
1383                 }
1384
1385                 if(pm && !pm2) {
1386                         *fra1 = 0;
1387                         *fra2 = pm->frame;
1388                 }
1389                 else {
1390                         *fra1 = pm->frame;
1391                         *fra2 = pm2->frame;
1392                 }
1393         }
1394 }
1395
1396 static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra)
1397 {
1398         PTCacheFile *pf = ptcache_file_open(pid, PTCACHE_FILE_READ, cfra);
1399         PTCacheMem *pm = NULL;
1400         unsigned int i, error = 0;
1401
1402         if(pf == NULL)
1403                 return NULL;
1404
1405         if(!ptcache_file_header_begin_read(pf))
1406                 error = 1;
1407
1408         if(!error && (pf->type != pid->type || !pid->read_header(pf)))
1409                 error = 1;
1410
1411         if(!error) {
1412                 pm = MEM_callocN(sizeof(PTCacheMem), "Pointcache mem");
1413
1414                 pm->totpoint = pf->totpoint;
1415                 pm->data_types = pf->data_types;
1416                 pm->frame = pf->frame;
1417
1418                 ptcache_data_alloc(pm);
1419
1420                 if(pf->flag & PTCACHE_TYPEFLAG_COMPRESS) {
1421                         for(i=0; i<BPHYS_TOT_DATA; i++) {
1422                                 unsigned int out_len = pm->totpoint*ptcache_data_size[i];
1423                                 if(pf->data_types & (1<<i))
1424                                         ptcache_file_compressed_read(pf, (unsigned char*)(pm->data[i]), out_len);
1425                         }
1426                 }
1427                 else {
1428                         BKE_ptcache_mem_pointers_init(pm);
1429                         ptcache_file_pointers_init(pf);
1430
1431                         for(i=0; i<pm->totpoint; i++) {
1432                                 if(!ptcache_file_data_read(pf)) {
1433                                         error = 1;
1434                                         break;
1435                                 }
1436                                 ptcache_data_copy(pf->cur, pm->cur);
1437                                 BKE_ptcache_mem_pointers_incr(pm);
1438                         }
1439                 }
1440         }
1441
1442         if(!error && pf->flag & PTCACHE_TYPEFLAG_EXTRADATA) {
1443                 unsigned int extratype = 0;
1444
1445                 while(ptcache_file_read(pf, &extratype, 1, sizeof(unsigned int))) {
1446                         PTCacheExtra *extra = MEM_callocN(sizeof(PTCacheExtra), "Pointcache extradata");
1447
1448                         extra->type = extratype;
1449
1450                         ptcache_file_read(pf, &extra->totdata, 1, sizeof(unsigned int));
1451
1452                         extra->data = MEM_callocN(extra->totdata * ptcache_extra_datasize[extra->type], "Pointcache extradata->data");
1453
1454                         if(pf->flag & PTCACHE_TYPEFLAG_COMPRESS)
1455                                 ptcache_file_compressed_read(pf, (unsigned char*)(extra->data), extra->totdata*ptcache_extra_datasize[extra->type]);
1456                         else
1457                                 ptcache_file_read(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]);
1458
1459                         BLI_addtail(&pm->extradata, extra);
1460                 }
1461         }
1462
1463         if(error && pm) {
1464                 ptcache_data_free(pm);
1465                 ptcache_extra_free(pm);
1466                 MEM_freeN(pm);
1467                 pm = NULL;
1468         }
1469
1470         ptcache_file_close(pf);
1471
1472         if (error && G.f & G_DEBUG) 
1473                 printf("Error reading from disk cache\n");
1474         
1475         return pm;
1476 }
1477 static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm)
1478 {
1479         PTCacheFile *pf = NULL;
1480         unsigned int i, error = 0;
1481         
1482         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, pm->frame);
1483
1484         pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, pm->frame);
1485
1486         if(pf==NULL) {
1487                 if (G.f & G_DEBUG) 
1488                         printf("Error opening disk cache file for writing\n");
1489                 return 0;
1490         }
1491
1492         pf->data_types = pm->data_types;
1493         pf->totpoint = pm->totpoint;
1494         pf->type = pid->type;
1495         pf->flag = 0;
1496         
1497         if(pm->extradata.first)
1498                 pf->flag |= PTCACHE_TYPEFLAG_EXTRADATA;
1499         
1500         if(pid->cache->compression)
1501                 pf->flag |= PTCACHE_TYPEFLAG_COMPRESS;
1502
1503         if(!ptcache_file_header_begin_write(pf) || !pid->write_header(pf))
1504                 error = 1;
1505
1506         if(!error) {
1507                 if(pid->cache->compression) {
1508                         for(i=0; i<BPHYS_TOT_DATA; i++) {
1509                                 if(pm->data[i]) {
1510                                         unsigned int in_len = pm->totpoint*ptcache_data_size[i];
1511                                         unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
1512                                         ptcache_file_compressed_write(pf, (unsigned char*)(pm->data[i]), in_len, out, pid->cache->compression);
1513                                         MEM_freeN(out);
1514                                 }
1515                         }
1516                 }
1517                 else {
1518                         BKE_ptcache_mem_pointers_init(pm);
1519                         ptcache_file_pointers_init(pf);
1520
1521                         for(i=0; i<pm->totpoint; i++) {
1522                                 ptcache_data_copy(pm->cur, pf->cur);
1523                                 if(!ptcache_file_data_write(pf)) {
1524                                         error = 1;
1525                                         break;
1526                                 }
1527                                 BKE_ptcache_mem_pointers_incr(pm);
1528                         }
1529                 }
1530         }
1531
1532         if(!error && pm->extradata.first) {
1533                 PTCacheExtra *extra = pm->extradata.first;
1534
1535                 for(; extra; extra=extra->next) {
1536                         if(extra->data == NULL || extra->totdata == 0)
1537                                 continue;
1538
1539                         ptcache_file_write(pf, &extra->type, 1, sizeof(unsigned int));
1540                         ptcache_file_write(pf, &extra->totdata, 1, sizeof(unsigned int));
1541
1542                         if(pid->cache->compression) {
1543                                 unsigned int in_len = extra->totdata * ptcache_extra_datasize[extra->type];
1544                                 unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
1545                                 ptcache_file_compressed_write(pf, (unsigned char*)(extra->data), in_len, out, pid->cache->compression);
1546                                 MEM_freeN(out);
1547                         }
1548                         else {
1549                                 ptcache_file_write(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]);
1550                         }
1551                 }
1552         }
1553
1554         ptcache_file_close(pf);
1555         
1556         if (error && G.f & G_DEBUG) 
1557                 printf("Error writing to disk cache\n");
1558
1559         return error==0;
1560 }
1561
1562 static int ptcache_read_stream(PTCacheID *pid, int cfra)
1563 {
1564         PTCacheFile *pf = ptcache_file_open(pid, PTCACHE_FILE_READ, cfra);
1565         int error = 0;
1566
1567         if(pid->read_stream == NULL)
1568                 return 0;
1569
1570         if(pf == NULL) {
1571                 if (G.f & G_DEBUG) 
1572                         printf("Error opening disk cache file for reading\n");
1573                 return 0;
1574         }
1575
1576         if(!ptcache_file_header_begin_read(pf))
1577                 error = 1;
1578
1579         if(!error && (pf->type != pid->type || !pid->read_header(pf)))
1580                 error = 1;
1581
1582         if(!error && pf->totpoint != pid->totpoint(pid->calldata, cfra))
1583                 error = 1;
1584
1585         if(!error) {
1586                 ptcache_file_pointers_init(pf);
1587
1588                 // we have stream reading here
1589                 pid->read_stream(pf, pid->calldata);
1590         }
1591
1592         ptcache_file_close(pf);
1593         
1594         return error == 0;
1595 }
1596 static int ptcache_read(PTCacheID *pid, int cfra)
1597 {
1598         PTCacheMem *pm = NULL;
1599         int i;
1600         int *index = &i;
1601
1602         /* get a memory cache to read from */
1603         if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1604                 pm = ptcache_disk_frame_to_mem(pid, cfra);
1605         }
1606         else {
1607                 pm = pid->cache->mem_cache.first;
1608                 
1609                 while(pm && pm->frame != cfra)
1610                         pm = pm->next;
1611         }
1612
1613         /* read the cache */
1614         if(pm) {
1615                 int totpoint = pm->totpoint;
1616
1617                 if((pid->data_types & (1<<BPHYS_DATA_INDEX)) == 0)
1618                         totpoint = MIN2(totpoint, pid->totpoint(pid->calldata, cfra));
1619
1620                 BKE_ptcache_mem_pointers_init(pm);
1621
1622                 for(i=0; i<totpoint; i++) {
1623                         if(pm->data_types & (1<<BPHYS_DATA_INDEX))
1624                                 index = pm->cur[BPHYS_DATA_INDEX];
1625
1626                         pid->read_point(*index, pid->calldata, pm->cur, (float)pm->frame, NULL);
1627                 
1628                         BKE_ptcache_mem_pointers_incr(pm);
1629                 }
1630
1631                 if(pid->read_extra_data && pm->extradata.first)
1632                         pid->read_extra_data(pid->calldata, pm, (float)pm->frame);
1633
1634                 /* clean up temporary memory cache */
1635                 if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1636                         ptcache_data_free(pm);
1637                         ptcache_extra_free(pm);
1638                         MEM_freeN(pm);
1639                 }
1640         }
1641
1642         return 1;
1643 }
1644 static int ptcache_interpolate(PTCacheID *pid, float cfra, int cfra1, int cfra2)
1645 {
1646         PTCacheMem *pm = NULL;
1647         int i;
1648         int *index = &i;
1649
1650         /* get a memory cache to read from */
1651         if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1652                 pm = ptcache_disk_frame_to_mem(pid, cfra2);
1653         }
1654         else {
1655                 pm = pid->cache->mem_cache.first;
1656                 
1657                 while(pm && pm->frame != cfra2)
1658                         pm = pm->next;
1659         }
1660
1661         /* read the cache */
1662         if(pm) {
1663                 int totpoint = pm->totpoint;
1664
1665                 if((pid->data_types & (1<<BPHYS_DATA_INDEX)) == 0)
1666                         totpoint = MIN2(totpoint, pid->totpoint(pid->calldata, (int)cfra));
1667
1668                 BKE_ptcache_mem_pointers_init(pm);
1669
1670                 for(i=0; i<totpoint; i++) {
1671                         if(pm->data_types & (1<<BPHYS_DATA_INDEX))
1672                                 index = pm->cur[BPHYS_DATA_INDEX];
1673
1674                         pid->interpolate_point(*index, pid->calldata, pm->cur, cfra, (float)cfra1, (float)cfra2, NULL);
1675                         BKE_ptcache_mem_pointers_incr(pm);
1676                 }
1677
1678                 if(pid->interpolate_extra_data && pm->extradata.first)
1679                         pid->interpolate_extra_data(pid->calldata, pm, cfra, (float)cfra1, (float)cfra2);
1680
1681                 /* clean up temporary memory cache */
1682                 if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1683                         ptcache_data_free(pm);
1684                         ptcache_extra_free(pm);
1685                         MEM_freeN(pm);
1686                 }
1687         }
1688
1689         return 1;
1690 }
1691 /* reads cache from disk or memory */
1692 /* possible to get old or interpolated result */
1693 int BKE_ptcache_read(PTCacheID *pid, float cfra)
1694 {
1695         int cfrai = (int)cfra, cfra1=0, cfra2=0;
1696         int ret = 0;
1697
1698         /* nothing to read to */
1699         if(pid->totpoint(pid->calldata, cfrai) == 0)
1700                 return 0;
1701
1702         if(pid->cache->flag & PTCACHE_READ_INFO) {
1703                 pid->cache->flag &= ~PTCACHE_READ_INFO;
1704                 ptcache_read(pid, 0);
1705         }
1706
1707         /* first check if we have the actual frame cached */
1708         if(cfra == (float)cfrai && BKE_ptcache_id_exist(pid, cfrai))
1709                 cfra1 = cfrai;
1710
1711         /* no exact cache frame found so try to find cached frames around cfra */
1712         if(cfra1 == 0)
1713                 ptcache_find_frames_around(pid, cfrai, &cfra1, &cfra2);
1714
1715         if(cfra1 == 0 && cfra2 == 0)
1716                 return 0;
1717
1718         /* don't read old cache if already simulated past cached frame */
1719         if(cfra1 == 0 && cfra2 && cfra2 <= pid->cache->simframe)
1720                 return 0;
1721         if(cfra1 && cfra1 == cfra2)
1722                 return 0;
1723
1724         if(cfra1) {
1725                 if(pid->read_stream)
1726                         ptcache_read_stream(pid, cfra1);
1727                 else if(pid->read_point)
1728                         ptcache_read(pid, cfra1);
1729         }
1730
1731         if(cfra2) {
1732                 if(pid->read_stream)
1733                         ptcache_read_stream(pid, cfra2);
1734                 else if(pid->read_point) {
1735                         if(cfra1 && cfra2 && pid->interpolate_point)
1736                                 ptcache_interpolate(pid, cfra, cfra1, cfra2);
1737                         else
1738                                 ptcache_read(pid, cfra2);
1739                 }
1740         }
1741
1742         if(cfra1)
1743                 ret = (cfra2 ? PTCACHE_READ_INTERPOLATED : PTCACHE_READ_EXACT);
1744         else if(cfra2) {
1745                 ret = PTCACHE_READ_OLD;
1746                 pid->cache->simframe = cfra2;
1747         }
1748
1749         if((pid->cache->flag & PTCACHE_QUICK_CACHE)==0) {
1750                 cfrai = (int)cfra;
1751                 /* clear invalid cache frames so that better stuff can be simulated */
1752                 if(pid->cache->flag & PTCACHE_OUTDATED) {
1753                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai);
1754                 }
1755                 else if(pid->cache->flag & PTCACHE_FRAMES_SKIPPED) {
1756                         if(cfra <= pid->cache->last_exact)
1757                                 pid->cache->flag &= ~PTCACHE_FRAMES_SKIPPED;
1758
1759                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, MAX2(cfrai, pid->cache->last_exact));
1760                 }
1761         }
1762
1763         return ret;
1764 }
1765 static int ptcache_write_stream(PTCacheID *pid, int cfra, int totpoint)
1766 {
1767         PTCacheFile *pf = NULL;
1768         int error = 0;
1769         
1770         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, cfra);
1771
1772         pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, cfra);
1773
1774         if(pf==NULL) {
1775                 if (G.f & G_DEBUG) 
1776                         printf("Error opening disk cache file for writing\n");
1777                 return 0;
1778         }
1779
1780         pf->data_types = pid->data_types;
1781         pf->totpoint = totpoint;
1782         pf->type = pid->type;
1783         pf->flag = 0;
1784
1785         if(!error && (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf)))
1786                 error = 1;
1787
1788         if(!error && pid->write_stream)
1789                 pid->write_stream(pf, pid->calldata);
1790
1791         ptcache_file_close(pf);
1792
1793         if (error && G.f & G_DEBUG) 
1794                 printf("Error writing to disk cache\n");
1795
1796         return error == 0;
1797 }
1798 static int ptcache_write(PTCacheID *pid, int cfra, int overwrite)
1799 {
1800         PointCache *cache = pid->cache;
1801         PTCacheMem *pm=NULL, *pm2=NULL;
1802         int totpoint = pid->totpoint(pid->calldata, cfra);
1803         int i, error = 0;
1804
1805         pm = MEM_callocN(sizeof(PTCacheMem), "Pointcache mem");
1806
1807         pm->totpoint = pid->totwrite(pid->calldata, cfra);
1808         pm->data_types = cfra ? pid->data_types : pid->info_types;
1809
1810         ptcache_data_alloc(pm);
1811         BKE_ptcache_mem_pointers_init(pm);
1812
1813         if(overwrite) {
1814                 if(cache->flag & PTCACHE_DISK_CACHE) {
1815                         int fra = cfra-1;
1816
1817                         while(fra >= cache->startframe && !BKE_ptcache_id_exist(pid, fra))
1818                                 fra--;
1819                         
1820                         pm2 = ptcache_disk_frame_to_mem(pid, fra);
1821                 }
1822                 else
1823                         pm2 = cache->mem_cache.last;
1824         }
1825
1826         if(pid->write_point) {
1827                 for(i=0; i<totpoint; i++) {
1828                         int write = pid->write_point(i, pid->calldata, pm->cur, cfra);
1829                         if(write) {
1830                                 BKE_ptcache_mem_pointers_incr(pm);
1831
1832                                 /* newly born particles have to be copied to previous cached frame */
1833                                 if(overwrite && write == 2 && pm2 && BKE_ptcache_mem_pointers_seek(i, pm2))
1834                                         pid->write_point(i, pid->calldata, pm2->cur, cfra);
1835                         }
1836                 }
1837         }
1838
1839         if(pid->write_extra_data)
1840                 pid->write_extra_data(pid->calldata, pm, cfra);
1841
1842         pm->frame = cfra;
1843
1844         if(cache->flag & PTCACHE_DISK_CACHE) {
1845                 error += !ptcache_mem_frame_to_disk(pid, pm);
1846
1847                 if(pm) {
1848                         ptcache_data_free(pm);
1849                         ptcache_extra_free(pm);
1850                         MEM_freeN(pm);
1851                 }
1852
1853                 if(pm2) {
1854                         error += !ptcache_mem_frame_to_disk(pid, pm2);
1855                         ptcache_data_free(pm2);
1856                         ptcache_extra_free(pm2);
1857                         MEM_freeN(pm2);
1858                 }
1859         }
1860         else {
1861                 BLI_addtail(&cache->mem_cache, pm);
1862         }
1863
1864         return error;
1865 }
1866 static int ptcache_write_needed(PTCacheID *pid, int cfra, int *overwrite)
1867 {
1868         PointCache *cache = pid->cache;
1869         int ofra = 0, efra = cache->endframe;
1870
1871         /* allways start from scratch on the first frame */
1872         if(cfra && cfra == cache->startframe) {
1873                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, cfra);
1874                 cache->flag &= ~PTCACHE_REDO_NEEDED;
1875                 return 1;
1876         }
1877
1878         if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1879                 if(cfra==0 && cache->startframe > 0)
1880                         return 1;
1881
1882                                 /* find last cached frame */
1883                 while(efra > cache->startframe && !BKE_ptcache_id_exist(pid, efra))
1884                         efra--;
1885
1886                 /* find second last cached frame */
1887                 ofra = efra-1;
1888                 while(ofra > cache->startframe && !BKE_ptcache_id_exist(pid, ofra))
1889                         ofra--;
1890         }
1891         else {
1892                 PTCacheMem *pm = cache->mem_cache.last;
1893                 /* don't write info file in memory */
1894                 if(cfra == 0)
1895                         return 0;
1896
1897                 if(pm == NULL)
1898                         return 1;
1899
1900                 efra = pm->frame;
1901                 ofra = (pm->prev ? pm->prev->frame : efra - cache->step);
1902         }
1903
1904         if(efra >= cache->startframe && cfra > efra) {
1905                 if(ofra >= cache->startframe && efra - ofra < cache->step) {
1906                         /* overwrite previous frame */
1907                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, efra);
1908                         *overwrite = 1;
1909                 }
1910                 return 1;
1911         }
1912
1913         return 0;
1914 }
1915 /* writes cache to disk or memory */
1916 int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra)
1917 {
1918         PointCache *cache = pid->cache;
1919         int totpoint = pid->totpoint(pid->calldata, cfra);
1920         int overwrite = 0, error = 0;
1921
1922         if(totpoint == 0 || (cfra ? pid->data_types == 0 : pid->info_types == 0))
1923                 return 0;
1924
1925         if(ptcache_write_needed(pid, cfra, &overwrite)==0)
1926                 return 0;
1927
1928         if(pid->write_stream) {
1929                 ptcache_write_stream(pid, cfra, totpoint);
1930         }
1931         else if(pid->write_point) {
1932                 error += ptcache_write(pid, cfra, overwrite);
1933         }
1934
1935         /* Mark frames skipped if more than 1 frame forwards since last non-skipped frame. */
1936         if(cfra - cache->last_exact == 1 || cfra == cache->startframe) {
1937                 cache->last_exact = cfra;
1938                 cache->flag &= ~PTCACHE_FRAMES_SKIPPED;
1939         }
1940         /* Don't mark skipped when writing info file (frame 0) */
1941         else if(cfra)
1942                 cache->flag |= PTCACHE_FRAMES_SKIPPED;
1943
1944         /* Update timeline cache display */
1945         if(cfra && cache->cached_frames)
1946                 cache->cached_frames[cfra-cache->startframe] = 1;
1947
1948         BKE_ptcache_update_info(pid);
1949
1950         return !error;
1951 }
1952 /* youll need to close yourself after!
1953  * mode - PTCACHE_CLEAR_ALL, 
1954
1955 */
1956 /* Clears & resets */
1957 void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra)
1958 {
1959         unsigned int len; /* store the length of the string */
1960         unsigned int sta, end;
1961
1962         /* mode is same as fopen's modes */
1963         DIR *dir; 
1964         struct dirent *de;
1965         char path[MAX_PTCACHE_PATH];
1966         char filename[MAX_PTCACHE_FILE];
1967         char path_full[MAX_PTCACHE_FILE];
1968         char ext[MAX_PTCACHE_PATH];
1969
1970         if(!pid || !pid->cache || pid->cache->flag & PTCACHE_BAKED)
1971                 return;
1972
1973         sta = pid->cache->startframe;
1974         end = pid->cache->endframe;
1975
1976 #ifndef DURIAN_POINTCACHE_LIB_OK
1977         /* don't allow clearing for linked objects */
1978         if(pid->ob->id.lib)
1979                 return;
1980 #endif
1981
1982         /*if (!G.relbase_valid) return; *//* save blend file before using pointcache */
1983         
1984         /* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */
1985         switch (mode) {
1986         case PTCACHE_CLEAR_ALL:
1987         case PTCACHE_CLEAR_BEFORE:      
1988         case PTCACHE_CLEAR_AFTER:
1989                 if(pid->cache->flag & PTCACHE_DISK_CACHE) {
1990                         ptcache_path(pid, path);
1991                         
1992                         len = ptcache_filename(pid, filename, cfra, 0, 0); /* no path */
1993                         
1994                         dir = opendir(path);
1995                         if (dir==NULL)
1996                                 return;
1997
1998                         snprintf(ext, sizeof(ext), "_%02d"PTCACHE_EXT, pid->stack_index);
1999                         
2000                         while ((de = readdir(dir)) != NULL) {
2001                                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
2002                                         if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
2003                                                 if (mode == PTCACHE_CLEAR_ALL) {
2004                                                         pid->cache->last_exact = MIN2(pid->cache->startframe, 0);
2005                                                         BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name);
2006                                                         BLI_delete(path_full, 0, 0);
2007                                                 } else {
2008                                                         /* read the number of the file */
2009                                                         unsigned int frame, len2 = (int)strlen(de->d_name);
2010                                                         char num[7];
2011
2012                                                         if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
2013                                                                 BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
2014                                                                 frame = atoi(num);
2015                                                                 
2016                                                                 if((mode==PTCACHE_CLEAR_BEFORE && frame < cfra) || 
2017                                                                 (mode==PTCACHE_CLEAR_AFTER && frame > cfra)     ) {
2018                                                                         
2019                                                                         BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name);
2020                                                                         BLI_delete(path_full, 0, 0);
2021                                                                         if(pid->cache->cached_frames && frame >=sta && frame <= end)
2022                                                                                 pid->cache->cached_frames[frame-sta] = 0;
2023                                                                 }
2024                                                         }
2025                                                 }
2026                                         }
2027                                 }
2028                         }
2029                         closedir(dir);
2030
2031                         if(mode == PTCACHE_CLEAR_ALL && pid->cache->cached_frames)
2032                                 memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames));
2033                 }
2034                 else {
2035                         PTCacheMem *pm= pid->cache->mem_cache.first;
2036                         PTCacheMem *link= NULL;
2037
2038                         if(mode == PTCACHE_CLEAR_ALL) {
2039                                 /*we want startframe if the cache starts before zero*/
2040                                 pid->cache->last_exact = MIN2(pid->cache->startframe, 0);
2041                                 for(; pm; pm=pm->next) {
2042                                         ptcache_data_free(pm);
2043                                         ptcache_extra_free(pm);
2044                                 }
2045                                 BLI_freelistN(&pid->cache->mem_cache);
2046
2047                                 if(pid->cache->cached_frames) 
2048                                         memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames));
2049                         } else {
2050                                 while(pm) {
2051                                         if((mode==PTCACHE_CLEAR_BEFORE && pm->frame < cfra)     || 
2052                                         (mode==PTCACHE_CLEAR_AFTER && pm->frame > cfra) ) {
2053                                                 link = pm;
2054                                                 if(pid->cache->cached_frames && pm->frame >=sta && pm->frame <= end)
2055                                                         pid->cache->cached_frames[pm->frame-sta] = 0;
2056                                                 ptcache_data_free(pm);
2057                                                 ptcache_extra_free(pm);
2058                                                 pm = pm->next;
2059                                                 BLI_freelinkN(&pid->cache->mem_cache, link);
2060                                         }
2061                                         else
2062                                                 pm = pm->next;
2063                                 }
2064                         }
2065                 }
2066                 break;
2067                 
2068         case PTCACHE_CLEAR_FRAME:
2069                 if(pid->cache->flag & PTCACHE_DISK_CACHE) {
2070                         if(BKE_ptcache_id_exist(pid, cfra)) {
2071                                 ptcache_filename(pid, filename, cfra, 1, 1); /* no path */
2072                                 BLI_delete(filename, 0, 0);
2073                         }
2074                 }
2075                 else {
2076                         PTCacheMem *pm = pid->cache->mem_cache.first;
2077
2078                         for(; pm; pm=pm->next) {
2079                                 if(pm->frame == cfra) {
2080                                         ptcache_data_free(pm);
2081                                         ptcache_extra_free(pm);
2082                                         BLI_freelinkN(&pid->cache->mem_cache, pm);
2083                                         break;
2084                                 }
2085                         }
2086                 }
2087                 if(pid->cache->cached_frames && cfra>=sta && cfra<=end)
2088                         pid->cache->cached_frames[cfra-sta] = 0;
2089                 break;
2090         }
2091
2092         BKE_ptcache_update_info(pid);
2093 }
2094 int  BKE_ptcache_id_exist(PTCacheID *pid, int cfra)
2095 {
2096         if(!pid->cache)
2097                 return 0;
2098
2099         if(cfra<pid->cache->startframe || cfra > pid->cache->endframe)
2100                 return 0;
2101
2102         if(pid->cache->cached_frames && pid->cache->cached_frames[cfra-pid->cache->startframe]==0)
2103                 return 0;
2104         
2105         if(pid->cache->flag & PTCACHE_DISK_CACHE) {
2106                 char filename[MAX_PTCACHE_FILE];
2107                 
2108                 ptcache_filename(pid, filename, cfra, 1, 1);
2109
2110                 return BLI_exists(filename);
2111         }
2112         else {
2113                 PTCacheMem *pm = pid->cache->mem_cache.first;
2114
2115                 for(; pm; pm=pm->next) {
2116                         if(pm->frame==cfra)
2117                                 return 1;
2118                 }
2119                 return 0;
2120         }
2121 }
2122 void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startframe, int *endframe, float *timescale)
2123 {
2124         Object *ob;
2125         PointCache *cache;
2126         float offset, time, nexttime;
2127
2128         /* TODO: this has to be sorter out once bsystem_time gets redone, */
2129         /*       now caches can handle interpolating etc. too - jahka */
2130
2131         /* time handling for point cache:
2132          * - simulation time is scaled by result of bsystem_time
2133          * - for offsetting time only time offset is taken into account, since
2134          *   that's always the same and can't be animated. a timeoffset which
2135          *   varies over time is not simpe to support.
2136          * - field and motion blur offsets are currently ignored, proper solution
2137          *   is probably to interpolate results from two frames for that ..
2138          */
2139
2140         ob= pid->ob;
2141         cache= pid->cache;
2142
2143         if(timescale) {
2144                 time= bsystem_time(scene, ob, cfra, 0.0f);
2145                 nexttime= bsystem_time(scene, ob, cfra+1.0f, 0.0f);
2146
2147                 *timescale= MAX2(nexttime - time, 0.0f);
2148         }
2149
2150         if(startframe && endframe) {
2151                 *startframe= cache->startframe;
2152                 *endframe= cache->endframe;
2153
2154                 // XXX ipoflag is depreceated - old animation system stuff
2155                 if (/*(ob->ipoflag & OB_OFFS_PARENT) &&*/ (ob->partype & PARSLOW)==0) {
2156                         offset= give_timeoffset(ob);
2157
2158                         *startframe += (int)(offset+0.5f);
2159                         *endframe += (int)(offset+0.5f);
2160                 }
2161         }
2162
2163         /* verify cached_frames array is up to date */
2164         if(cache->cached_frames) {
2165                 if(MEM_allocN_len(cache->cached_frames) != sizeof(char) * (cache->endframe-cache->startframe+1)) {
2166                         MEM_freeN(cache->cached_frames);
2167                         cache->cached_frames = NULL;
2168                 }       
2169         }
2170
2171         if(cache->cached_frames==NULL && cache->endframe > cache->startframe) {
2172                 unsigned int sta=cache->startframe;
2173                 unsigned int end=cache->endframe;
2174
2175                 cache->cached_frames = MEM_callocN(sizeof(char) * (cache->endframe-cache->startframe+1), "cached frames array");
2176
2177                 if(pid->cache->flag & PTCACHE_DISK_CACHE) {
2178                         /* mode is same as fopen's modes */
2179                         DIR *dir; 
2180                         struct dirent *de;
2181                         char path[MAX_PTCACHE_PATH];
2182                         char filename[MAX_PTCACHE_FILE];
2183                         char ext[MAX_PTCACHE_PATH];
2184                         unsigned int len; /* store the length of the string */
2185
2186                         ptcache_path(pid, path);
2187                         
2188                         len = ptcache_filename(pid, filename, (int)cfra, 0, 0); /* no path */
2189                         
2190                         dir = opendir(path);
2191                         if (dir==NULL)
2192                                 return;
2193
2194                         snprintf(ext, sizeof(ext), "_%02d"PTCACHE_EXT, pid->stack_index);
2195                         
2196                         while ((de = readdir(dir)) != NULL) {
2197                                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
2198                                         if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
2199                                                 /* read the number of the file */
2200                                                 unsigned int frame, len2 = (int)strlen(de->d_name);
2201                                                 char num[7];
2202
2203                                                 if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
2204                                                         BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
2205                                                         frame = atoi(num);
2206                                                         
2207                                                         if(frame >= sta && frame <= end)
2208                                                                 cache->cached_frames[frame-sta] = 1;
2209                                                 }
2210                                         }
2211                                 }
2212                         }
2213                         closedir(dir);
2214                 }
2215                 else {
2216                         PTCacheMem *pm= pid->cache->mem_cache.first;
2217
2218                         while(pm) {
2219                                 if(pm->frame >= sta && pm->frame <= end)
2220                                         cache->cached_frames[pm->frame-sta] = 1;
2221                                 pm = pm->next;
2222                         }
2223                 }
2224         }
2225 }
2226 int  BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode)
2227 {
2228         PointCache *cache;
2229         int reset, clear, after;
2230
2231         if(!pid->cache)
2232                 return 0;
2233
2234         cache= pid->cache;
2235         reset= 0;
2236         clear= 0;
2237         after= 0;
2238
2239         if(mode == PTCACHE_RESET_DEPSGRAPH) {
2240                 if(!(cache->flag & PTCACHE_BAKED) && !BKE_ptcache_get_continue_physics()) {
2241                         if(cache->flag & PTCACHE_QUICK_CACHE)
2242                                 clear= 1;
2243
2244                         after= 1;
2245                 }
2246
2247                 cache->flag |= PTCACHE_OUTDATED;
2248         }
2249         else if(mode == PTCACHE_RESET_BAKED) {
2250                 if(!BKE_ptcache_get_continue_physics()) {
2251                         reset= 1;
2252                         clear= 1;
2253                 }
2254                 else
2255                         cache->flag |= PTCACHE_OUTDATED;
2256         }
2257         else if(mode == PTCACHE_RESET_OUTDATED) {
2258                 reset = 1;
2259
2260                 if(cache->flag & PTCACHE_OUTDATED && !(cache->flag & PTCACHE_BAKED)) {
2261                         clear= 1;
2262                         cache->flag &= ~PTCACHE_OUTDATED;
2263                 }
2264         }
2265
2266         if(reset) {
2267                 BKE_ptcache_invalidate(cache);
2268                 cache->flag &= ~PTCACHE_REDO_NEEDED;
2269
2270                 if(pid->type == PTCACHE_TYPE_CLOTH)
2271                         cloth_free_modifier(pid->calldata);
2272                 else if(pid->type == PTCACHE_TYPE_SOFTBODY)
2273                         sbFreeSimulation(pid->calldata);
2274                 else if(pid->type == PTCACHE_TYPE_PARTICLES)
2275                         psys_reset(pid->calldata, PSYS_RESET_DEPSGRAPH);
2276                 else if(pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
2277                         smokeModifier_reset(pid->calldata);
2278                 else if(pid->type == PTCACHE_TYPE_SMOKE_HIGHRES)
2279                         smokeModifier_reset_turbulence(pid->calldata);
2280         }
2281         if(clear)
2282                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2283         else if(after)
2284                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, CFRA);
2285
2286         return (reset || clear || after);
2287 }
2288 int  BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode)
2289 {
2290         PTCacheID pid;
2291         ParticleSystem *psys;
2292         ModifierData *md;
2293         int reset, skip;
2294
2295         reset= 0;
2296         skip= 0;
2297
2298         if(ob->soft) {
2299                 BKE_ptcache_id_from_softbody(&pid, ob, ob->soft);
2300                 reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2301         }
2302
2303         for(psys=ob->particlesystem.first; psys; psys=psys->next) {
2304                 /* children or just redo can be calculated without reseting anything */
2305                 if(psys->recalc & PSYS_RECALC_REDO || psys->recalc & PSYS_RECALC_CHILD)
2306                         skip = 1;
2307                 /* Baked cloth hair has to be checked too, because we don't want to reset */
2308                 /* particles or cloth in that case -jahka */
2309                 else if(psys->clmd) {
2310                         BKE_ptcache_id_from_cloth(&pid, ob, psys->clmd);
2311                         if(mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) 
2312                                 reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2313                         else
2314                                 skip = 1;
2315                 }
2316
2317                 if(skip == 0 && psys->part) {
2318                         BKE_ptcache_id_from_particles(&pid, ob, psys);
2319                         reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2320                 }
2321         }
2322
2323         for(md=ob->modifiers.first; md; md=md->next) {
2324                 if(md->type == eModifierType_Cloth) {
2325                         BKE_ptcache_id_from_cloth(&pid, ob, (ClothModifierData*)md);
2326                         reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2327                 }
2328                 if(md->type == eModifierType_Smoke) {
2329                         SmokeModifierData *smd = (SmokeModifierData *)md;
2330                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
2331                         {
2332                                 BKE_ptcache_id_from_smoke(&pid, ob, (SmokeModifierData*)md);
2333                                 reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2334                         }
2335                 }
2336         }
2337
2338         if (ob->type == OB_ARMATURE)
2339                 BIK_clear_cache(ob->pose);
2340
2341         return reset;
2342 }
2343
2344 /* Use this when quitting blender, with unsaved files */
2345 void BKE_ptcache_remove(void)
2346 {
2347         char path[MAX_PTCACHE_PATH];
2348         char path_full[MAX_PTCACHE_PATH];
2349         int rmdir = 1;
2350         
2351         ptcache_path(NULL, path);
2352
2353         if (BLI_exist(path)) {
2354                 /* The pointcache dir exists? - remove all pointcache */
2355
2356                 DIR *dir; 
2357                 struct dirent *de;
2358
2359                 dir = opendir(path);
2360                 if (dir==NULL)
2361                         return;
2362                 
2363                 while ((de = readdir(dir)) != NULL) {
2364                         if( strcmp(de->d_name, ".")==0 || strcmp(de->d_name, "..")==0) {
2365                                 /* do nothing */
2366                         } else if (strstr(de->d_name, PTCACHE_EXT)) { /* do we have the right extension?*/
2367                                 BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name);
2368                                 BLI_delete(path_full, 0, 0);
2369                         } else {
2370                                 rmdir = 0; /* unknown file, dont remove the dir */
2371                         }
2372                 }
2373
2374                 closedir(dir);
2375         } else { 
2376                 rmdir = 0; /* path dosnt exist  */
2377         }
2378         
2379         if (rmdir) {
2380                 BLI_delete(path, 1, 0);
2381         }
2382 }
2383
2384 /* Continuous Interaction */
2385
2386 static int CONTINUE_PHYSICS = 0;
2387
2388 void BKE_ptcache_set_continue_physics(Main *bmain, Scene *scene, int enable)
2389 {
2390         Object *ob;
2391
2392         if(CONTINUE_PHYSICS != enable) {
2393                 CONTINUE_PHYSICS = enable;
2394
2395                 if(CONTINUE_PHYSICS == 0) {
2396                         for(ob=bmain->object.first; ob; ob=ob->id.next)
2397                                 if(BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_OUTDATED))
2398                                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2399                 }
2400         }
2401 }
2402
2403 int  BKE_ptcache_get_continue_physics(void)
2404 {
2405         return CONTINUE_PHYSICS;
2406 }
2407
2408 /* Point Cache handling */
2409
2410 PointCache *BKE_ptcache_add(ListBase *ptcaches)
2411 {
2412         PointCache *cache;
2413
2414         cache= MEM_callocN(sizeof(PointCache), "PointCache");
2415         cache->startframe= 1;
2416         cache->endframe= 250;
2417         cache->step= 10;
2418         cache->index = -1;
2419
2420         BLI_addtail(ptcaches, cache);
2421
2422         return cache;
2423 }
2424
2425 void BKE_ptcache_free_mem(ListBase *mem_cache)
2426 {
2427         PTCacheMem *pm = mem_cache->first;
2428
2429         if(pm) {
2430                 for(; pm; pm=pm->next) {
2431                         ptcache_data_free(pm);
2432                         ptcache_extra_free(pm);
2433                 }
2434
2435                 BLI_freelistN(mem_cache);
2436         }
2437 }
2438 void BKE_ptcache_free(PointCache *cache)
2439 {
2440         BKE_ptcache_free_mem(&cache->mem_cache);
2441         if(cache->edit && cache->free_edit)
2442                 cache->free_edit(cache->edit);
2443         if(cache->cached_frames)
2444                 MEM_freeN(cache->cached_frames);
2445         MEM_freeN(cache);
2446 }
2447 void BKE_ptcache_free_list(ListBase *ptcaches)
2448 {
2449         PointCache *cache = ptcaches->first;
2450
2451         while(cache) {
2452                 BLI_remlink(ptcaches, cache);
2453                 BKE_ptcache_free(cache);
2454                 cache = ptcaches->first;
2455         }
2456 }
2457
2458 static PointCache *ptcache_copy(PointCache *cache)
2459 {
2460         PointCache *ncache;
2461
2462         ncache= MEM_dupallocN(cache);
2463
2464         /* hmm, should these be copied over instead? */
2465         ncache->mem_cache.first = NULL;
2466         ncache->mem_cache.last = NULL;
2467         ncache->cached_frames = NULL;
2468         ncache->edit = NULL;
2469
2470         ncache->flag= 0;
2471         ncache->simframe= 0;
2472
2473         return ncache;
2474 }
2475 /* returns first point cache */
2476 PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, ListBase *ptcaches_old)
2477 {
2478         PointCache *cache = ptcaches_old->first;
2479
2480         ptcaches_new->first = ptcaches_new->last = NULL;
2481
2482         for(; cache; cache=cache->next)
2483                 BLI_addtail(ptcaches_new, ptcache_copy(cache));
2484
2485         return ptcaches_new->first;
2486 }
2487
2488
2489 /* Baking */
2490 void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene)
2491 {
2492         PTCacheBaker baker;
2493
2494         baker.bake=0;
2495         baker.break_data=NULL;
2496         baker.break_test=NULL;
2497         baker.pid=NULL;
2498         baker.progressbar=NULL;
2499         baker.progressend=NULL;
2500         baker.progresscontext=NULL;
2501         baker.render=0;
2502         baker.anim_init = 0;
2503         baker.main=bmain;
2504         baker.scene=scene;
2505         baker.quick_step=scene->physics_settings.quick_cache_step;
2506
2507         BKE_ptcache_bake(&baker);
2508 }
2509
2510 /* Simulation thread, no need for interlocks as data written in both threads
2511  are only unitary integers (I/O assumed to be atomic for them) */
2512 typedef struct {
2513         int break_operation;
2514         int thread_ended;
2515         int endframe;
2516         int step;
2517         int *cfra_ptr;
2518         Main *main;
2519         Scene *scene;
2520 } ptcache_bake_data;
2521
2522 static void ptcache_dt_to_str(char *str, double dtime)
2523 {
2524         if(dtime > 60.0) {
2525                 if(dtime > 3600.0)
2526                         sprintf(str, "%ih %im %is", (int)(dtime/3600), ((int)(dtime/60))%60, ((int)dtime) % 60);
2527                 else
2528                         sprintf(str, "%im %is", ((int)(dtime/60))%60, ((int)dtime) % 60);
2529         }
2530         else
2531                 sprintf(str, "%is", ((int)dtime) % 60);
2532 }
2533
2534 static void *ptcache_bake_thread(void *ptr) {
2535         int usetimer = 0, sfra, efra;
2536         double stime, ptime, ctime, fetd;
2537         char run[32], cur[32], etd[32];
2538
2539         ptcache_bake_data *data = (ptcache_bake_data*)ptr;
2540
2541         stime = ptime = PIL_check_seconds_timer();
2542         sfra = *data->cfra_ptr;
2543         efra = data->endframe;
2544
2545         for(; (*data->cfra_ptr <= data->endframe) && !data->break_operation; *data->cfra_ptr+=data->step) {
2546                 scene_update_for_newframe(data->main, data->scene, data->scene->lay);
2547                 if(G.background) {
2548                         printf("bake: frame %d :: %d\n", (int)*data->cfra_ptr, data->endframe);
2549                 }
2550                 else {
2551                         ctime = PIL_check_seconds_timer();
2552
2553                         fetd = (ctime-ptime)*(efra-*data->cfra_ptr)/data->step;
2554
2555                         if(usetimer || fetd > 60.0) {
2556                                 usetimer = 1;
2557
2558                                 ptcache_dt_to_str(cur, ctime-ptime);
2559                                 ptcache_dt_to_str(run, ctime-stime);
2560                                 ptcache_dt_to_str(etd, fetd);
2561
2562                                 printf("Baked for %s, current frame: %i/%i (%.3fs), ETC: %s          \r", run, *data->cfra_ptr-sfra+1, efra-sfra+1, ctime-ptime, etd);
2563                         }
2564                         ptime = ctime;
2565                 }
2566         }
2567
2568         if(usetimer) {
2569                 ptcache_dt_to_str(run, PIL_check_seconds_timer()-stime);
2570                 printf("Bake %s %s (%i frames simulated).                       \n", (data->break_operation ? "canceled after" : "finished in"), run, *data->cfra_ptr-sfra);
2571         }
2572
2573         data->thread_ended = TRUE;
2574         return NULL;
2575 }
2576
2577 /* if bake is not given run simulations to current frame */
2578 void BKE_ptcache_bake(PTCacheBaker* baker)
2579 {
2580         Main *bmain = baker->main;
2581         Scene *scene = baker->scene;
2582         Scene *sce_iter; /* SETLOOPER macro only */
2583         Base *base;
2584         ListBase pidlist;
2585         PTCacheID *pid = baker->pid;
2586         PointCache *cache = NULL;
2587         float frameleno = scene->r.framelen;
2588         int cfrao = CFRA;
2589         int startframe = MAXFRAME;
2590         int bake = baker->bake;
2591         int render = baker->render;
2592         ListBase threads;
2593         ptcache_bake_data thread_data;
2594         int progress, old_progress;
2595         
2596         thread_data.endframe = baker->anim_init ? scene->r.sfra : CFRA;
2597         thread_data.step = baker->quick_step;
2598         thread_data.cfra_ptr = &CFRA;
2599         thread_data.scene = baker->scene;
2600         thread_data.main = baker->main;
2601
2602         G.afbreek = 0;
2603
2604         /* set caches to baking mode and figure out start frame */
2605         if(pid) {
2606                 /* cache/bake a single object */
2607                 cache = pid->cache;
2608                 if((cache->flag & PTCACHE_BAKED)==0) {
2609                         if(pid->type==PTCACHE_TYPE_PARTICLES) {
2610                                 ParticleSystem *psys= pid->calldata;
2611
2612                                 /* a bit confusing, could make this work better in the UI */
2613                                 if(psys->part->type == PART_EMITTER)
2614                                         psys_get_pointcache_start_end(scene, pid->calldata, &cache->startframe, &cache->endframe);
2615                         }
2616                         else if(pid->type == PTCACHE_TYPE_SMOKE_HIGHRES) {
2617                                 /* get all pids from the object and search for smoke low res */
2618                                 ListBase pidlist2;
2619                                 PTCacheID *pid2;
2620                                 BKE_ptcache_ids_from_object(&pidlist2, pid->ob, scene, MAX_DUPLI_RECUR);
2621                                 for(pid2=pidlist2.first; pid2; pid2=pid2->next) {
2622                                         if(pid2->type == PTCACHE_TYPE_SMOKE_DOMAIN) 
2623                                         {
2624                                                 if(pid2->cache && !(pid2->cache->flag & PTCACHE_BAKED)) {
2625                                                         if(bake || pid2->cache->flag & PTCACHE_REDO_NEEDED)
2626                                                                 BKE_ptcache_id_clear(pid2, PTCACHE_CLEAR_ALL, 0);
2627                                                         if(bake) {
2628                                                                 pid2->cache->flag |= PTCACHE_BAKING;
2629                                                                 pid2->cache->flag &= ~PTCACHE_BAKED;
2630                                                         }
2631                                                 }
2632                                         }
2633                                 }
2634                                 BLI_freelistN(&pidlist2);
2635                         }
2636
2637                         if(bake || cache->flag & PTCACHE_REDO_NEEDED)
2638                                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2639
2640                         startframe = MAX2(cache->last_exact, cache->startframe);
2641
2642                         if(bake) {
2643                                 thread_data.endframe = cache->endframe;
2644                                 cache->flag |= PTCACHE_BAKING;
2645                         }
2646                         else {
2647                                 thread_data.endframe = MIN2(thread_data.endframe, cache->endframe);
2648                         }
2649
2650                         cache->flag &= ~PTCACHE_BAKED;
2651                 }
2652         }
2653         else for(SETLOOPER(scene, sce_iter, base)) {
2654                 /* cache/bake everything in the scene */
2655                 BKE_ptcache_ids_from_object(&pidlist, base->object, scene, MAX_DUPLI_RECUR);
2656
2657                 for(pid=pidlist.first; pid; pid=pid->next) {
2658                         cache = pid->cache;
2659                         if((cache->flag & PTCACHE_BAKED)==0) {
2660                                 if(pid->type==PTCACHE_TYPE_PARTICLES) {
2661                                         ParticleSystem *psys = (ParticleSystem*)pid->calldata;
2662                                         /* skip hair & keyed particles */
2663                                         if(psys->part->type == PART_HAIR || psys->part->phystype == PART_PHYS_KEYED)
2664                                                 continue;
2665
2666                                         psys_get_pointcache_start_end(scene, pid->calldata, &cache->startframe, &cache->endframe);
2667                                 }
2668
2669                                 if((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0)
2670                                         && ((cache->flag & PTCACHE_QUICK_CACHE)==0 || render || bake))
2671                                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2672
2673                                 startframe = MIN2(startframe, cache->startframe);
2674
2675                                 if(bake || render) {
2676                                         cache->flag |= PTCACHE_BAKING;
2677
2678                                         if(bake)
2679                                                 thread_data.endframe = MAX2(thread_data.endframe, cache->endframe);
2680                                 }
2681
2682                                 cache->flag &= ~PTCACHE_BAKED;
2683
2684                         }
2685                 }
2686                 BLI_freelistN(&pidlist);
2687         }
2688
2689         CFRA = startframe;
2690         scene->r.framelen = 1.0;
2691         thread_data.break_operation = FALSE;
2692         thread_data.thread_ended = FALSE;
2693         old_progress = -1;
2694
2695         WM_cursor_wait(1);
2696         
2697         if(G.background) {
2698                 ptcache_bake_thread((void*)&thread_data);
2699         }
2700         else {
2701                 BLI_init_threads(&threads, ptcache_bake_thread, 1);
2702                 BLI_insert_thread(&threads, (void*)&thread_data);
2703
2704                 while (thread_data.thread_ended == FALSE) {
2705
2706                         if(bake)
2707                                 progress = (int)(100.0f * (float)(CFRA - startframe)/(float)(thread_data.endframe-startframe));
2708                         else
2709                                 progress = CFRA;
2710
2711                         /* NOTE: baking should not redraw whole ui as this slows things down */
2712                         if ((baker->progressbar) && (progress != old_progress)) {
2713                                 baker->progressbar(baker->progresscontext, progress);
2714                                 old_progress = progress;
2715                         }
2716
2717                         /* Delay to lessen CPU load from UI thread */
2718                         PIL_sleep_ms(200);
2719
2720                         /* NOTE: breaking baking should leave calculated frames in cache, not clear it */
2721                         if(blender_test_break() && !thread_data.break_operation) {
2722                                 thread_data.break_operation = TRUE;
2723                                 if (baker->progressend)
2724                                         baker->progressend(baker->progresscontext);
2725                                 WM_cursor_wait(1);
2726                         }
2727                 }
2728
2729         BLI_end_threads(&threads);
2730         }
2731         /* clear baking flag */
2732         if(pid) {
2733                 cache->flag &= ~(PTCACHE_BAKING|PTCACHE_REDO_NEEDED);
2734                 cache->flag |= PTCACHE_SIMULATION_VALID;
2735                 if(bake) {
2736                         cache->flag |= PTCACHE_BAKED;
2737                         /* write info file */
2738                         if(cache->flag & PTCACHE_DISK_CACHE)
2739                                 BKE_ptcache_write(pid, 0);
2740                 }
2741         }
2742         else for(SETLOOPER(scene, sce_iter, base)) {
2743                 BKE_ptcache_ids_from_object(&pidlist, base->object, scene, MAX_DUPLI_RECUR);
2744
2745                 for(pid=pidlist.first; pid; pid=pid->next) {
2746                         /* skip hair particles */
2747                         if(pid->type==PTCACHE_TYPE_PARTICLES && ((ParticleSystem*)pid->calldata)->part->type == PART_HAIR)
2748                                 continue;
2749                 
2750                         cache = pid->cache;
2751
2752                         if(thread_data.step > 1)
2753                                 cache->flag &= ~(PTCACHE_BAKING|PTCACHE_OUTDATED);
2754                         else
2755                                 cache->flag &= ~(PTCACHE_BAKING|PTCACHE_REDO_NEEDED);
2756
2757                         cache->flag |= PTCACHE_SIMULATION_VALID;
2758
2759                         if(bake) {
2760                                 cache->flag |= PTCACHE_BAKED;
2761                                 if(cache->flag & PTCACHE_DISK_CACHE)
2762                                         BKE_ptcache_write(pid, 0);
2763                         }
2764                 }
2765                 BLI_freelistN(&pidlist);
2766         }
2767
2768         scene->r.framelen = frameleno;
2769         CFRA = cfrao;
2770         
2771         if(bake) /* already on cfra unless baking */
2772                 scene_update_for_newframe(bmain, scene, scene->lay);
2773
2774         if (thread_data.break_operation)
2775                 WM_cursor_wait(0);
2776         else if (baker->progressend)
2777                 baker->progressend(baker->progresscontext);
2778
2779         WM_cursor_wait(0);
2780
2781         /* TODO: call redraw all windows somehow */
2782 }
2783 /* Helpers */
2784 void BKE_ptcache_disk_to_mem(PTCacheID *pid)
2785 {
2786         PointCache *cache = pid->cache;
2787         PTCacheMem *pm = NULL;
2788         int baked = cache->flag & PTCACHE_BAKED;
2789         int cfra, sfra = cache->startframe, efra = cache->endframe;
2790
2791         /* Remove possible bake flag to allow clear */
2792         cache->flag &= ~PTCACHE_BAKED;
2793
2794         /* PTCACHE_DISK_CACHE flag was cleared already */
2795         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2796
2797         /* restore possible bake flag */
2798         cache->flag |= baked;
2799
2800         for(cfra=sfra; cfra <= efra; cfra++) {
2801                 pm = ptcache_disk_frame_to_mem(pid, cfra);
2802
2803                 if(pm)
2804                         BLI_addtail(&pid->cache->mem_cache, pm);
2805         }
2806 }
2807 void BKE_ptcache_mem_to_disk(PTCacheID *pid)
2808 {
2809         PointCache *cache = pid->cache;
2810         PTCacheMem *pm = cache->mem_cache.first;
2811         int baked = cache->flag & PTCACHE_BAKED;
2812
2813         /* Remove possible bake flag to allow clear */
2814         cache->flag &= ~PTCACHE_BAKED;
2815
2816         /* PTCACHE_DISK_CACHE flag was set already */
2817         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2818
2819         /* restore possible bake flag */
2820         cache->flag |= baked;
2821
2822         for(; pm; pm=pm->next) {
2823                 if(ptcache_mem_frame_to_disk(pid, pm)==0) {
2824                         cache->flag &= ~PTCACHE_DISK_CACHE;
2825                         break;
2826                 }
2827         }
2828
2829         /* write info file */
2830         if(cache->flag & PTCACHE_BAKED)
2831                 BKE_ptcache_write(pid, 0);
2832 }
2833 void BKE_ptcache_toggle_disk_cache(PTCacheID *pid)
2834 {
2835         PointCache *cache = pid->cache;
2836         int last_exact = cache->last_exact;
2837
2838         if (!G.relbase_valid){
2839                 cache->flag &= ~PTCACHE_DISK_CACHE;
2840                 if (G.f & G_DEBUG) 
2841                         printf("File must be saved before using disk cache!\n");
2842                 return;
2843         }
2844
2845         if(cache->cached_frames) {
2846                 MEM_freeN(cache->cached_frames);
2847                 cache->cached_frames=NULL;
2848         }
2849
2850         if(cache->flag & PTCACHE_DISK_CACHE)
2851                 BKE_ptcache_mem_to_disk(pid);
2852         else
2853                 BKE_ptcache_disk_to_mem(pid);
2854
2855         cache->flag ^= PTCACHE_DISK_CACHE;
2856         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2857         cache->flag ^= PTCACHE_DISK_CACHE;
2858         
2859         cache->last_exact = last_exact;
2860
2861         BKE_ptcache_id_time(pid, NULL, 0.0f, NULL, NULL, NULL);
2862
2863         BKE_ptcache_update_info(pid);
2864 }
2865
2866 void BKE_ptcache_disk_cache_rename(PTCacheID *pid, char *from, char *to)
2867 {
2868         char old_name[80];
2869         int len; /* store the length of the string */
2870         /* mode is same as fopen's modes */
2871         DIR *dir; 
2872         struct dirent *de;
2873         char path[MAX_PTCACHE_PATH];
2874         char old_filename[MAX_PTCACHE_FILE];
2875         char new_path_full[MAX_PTCACHE_FILE];
2876         char old_path_full[MAX_PTCACHE_FILE];
2877         char ext[MAX_PTCACHE_PATH];
2878
2879         /* save old name */
2880         strcpy(old_name, pid->cache->name);
2881
2882         /* get "from" filename */
2883         strcpy(pid->cache->name, from);
2884
2885         len = ptcache_filename(pid, old_filename, 0, 0, 0); /* no path */
2886
2887         ptcache_path(pid, path);
2888         dir = opendir(path);
2889         if(dir==NULL) {
2890                 strcpy(pid->cache->name, old_name);
2891                 return;
2892         }
2893
2894         snprintf(ext, sizeof(ext), "_%02d"PTCACHE_EXT, pid->stack_index);
2895
2896         /* put new name into cache */
2897         strcpy(pid->cache->name, to);
2898
2899         while ((de = readdir(dir)) != NULL) {
2900                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
2901                         if (strncmp(old_filename, de->d_name, len ) == 0) { /* do we have the right prefix */
2902                                 /* read the number of the file */
2903                                 int frame, len2 = (int)strlen(de->d_name);
2904                                 char num[7];
2905
2906                                 if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
2907                                         BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
2908                                         frame = atoi(num);
2909
2910                                         BLI_join_dirfile(old_path_full, sizeof(old_path_full), path, de->d_name);
2911                                         ptcache_filename(pid, new_path_full, frame, 1, 1);
2912                                         BLI_rename(old_path_full, new_path_full);
2913                                 }
2914                         }
2915                 }
2916         }
2917         closedir(dir);
2918
2919         strcpy(pid->cache->name, old_name);
2920 }
2921
2922 void BKE_ptcache_load_external(PTCacheID *pid)
2923 {
2924         /*todo*/
2925         PointCache *cache = pid->cache;
2926         int len; /* store the length of the string */
2927         int info = 0;
2928         int start = MAXFRAME;
2929         int end = -1;
2930
2931         /* mode is same as fopen's modes */
2932         DIR *dir; 
2933         struct dirent *de;
2934         char path[MAX_PTCACHE_PATH];
2935         char filename[MAX_PTCACHE_FILE];
2936         char ext[MAX_PTCACHE_PATH];
2937
2938         if(!cache)
2939                 return;
2940
2941         ptcache_path(pid, path);
2942         
2943         len = ptcache_filename(pid, filename, 1, 0, 0); /* no path */
2944         
2945         dir = opendir(path);
2946         if (dir==NULL)
2947                 return;
2948
2949         if(cache->index >= 0)
2950                 snprintf(ext, sizeof(ext), "_%02d"PTCACHE_EXT, cache->index);
2951         else
2952                 strcpy(ext, PTCACHE_EXT);
2953         
2954         while ((de = readdir(dir)) != NULL) {
2955                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
2956                         if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
2957                                 /* read the number of the file */
2958                                 int frame, len2 = (int)strlen(de->d_name);
2959                                 char num[7];
2960
2961                                 if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
2962                                         BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
2963                                         frame = atoi(num);
2964
2965                                         if(frame) {
2966                                                 start = MIN2(start, frame);
2967                                                 end = MAX2(end, frame);
2968                                         }
2969                                         else
2970                                                 info = 1;
2971                                 }
2972                         }
2973                 }
2974         }
2975         closedir(dir);
2976
2977         if(start != MAXFRAME) {
2978                 PTCacheFile *pf;
2979
2980                 cache->startframe = start;
2981                 cache->endframe = end;
2982                 cache->totpoint = 0;
2983
2984                 if(pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
2985                         ; /*necessary info in every file*/
2986                 /* read totpoint from info file (frame 0) */
2987                 else if(info) {
2988                         pf= ptcache_file_open(pid, PTCACHE_FILE_READ, 0);
2989
2990                         if(pf) {
2991                                 if(ptcache_file_header_begin_read(pf)) {
2992                                         if(pf->type == pid->type && pid->read_header(pf)) {
2993                                                 cache->totpoint = pf->totpoint;
2994                                                 cache->flag |= PTCACHE_READ_INFO;
2995                                         }
2996                                         else {
2997                                                 cache->totpoint = 0;
2998                                         }
2999                                 }
3000                                 ptcache_file_close(pf);
3001                         }
3002                 }
3003                 /* or from any old format cache file */
3004                 else {
3005                         float old_data[14];
3006                         int elemsize = ptcache_old_elemsize(pid);
3007                         pf= ptcache_file_open(pid, PTCACHE_FILE_READ, cache->startframe);
3008
3009                         if(pf) {
3010                                 while(ptcache_file_read(pf, old_data, 1, elemsize))
3011                                         cache->totpoint++;
3012                                 
3013                                 ptcache_file_close(pf);
3014                         }
3015                 }
3016                 cache->flag |= (PTCACHE_BAKED|PTCACHE_DISK_CACHE|PTCACHE_SIMULATION_VALID);
3017                 cache->flag &= ~(PTCACHE_OUTDATED|PTCACHE_FRAMES_SKIPPED);
3018         }
3019
3020         BKE_ptcache_update_info(pid);
3021 }
3022
3023 void BKE_ptcache_update_info(PTCacheID *pid)
3024 {
3025         PointCache *cache = pid->cache;
3026         PTCacheExtra *extra = NULL;
3027         int totframes = 0;
3028         char mem_info[64];
3029
3030         if(cache->flag & PTCACHE_EXTERNAL) {
3031                 int cfra = cache->startframe;
3032
3033                 for(; cfra<=cache->endframe; cfra++) {
3034                         if(BKE_ptcache_id_exist(pid, cfra))
3035                                 totframes++;
3036                 }
3037
3038                 /* smoke doesn't use frame 0 as info frame so can't check based on totpoint */
3039                 if(pid->type == PTCACHE_TYPE_SMOKE_DOMAIN && totframes)
3040                         sprintf(cache->info, "%i frames found!", totframes);
3041                 else if(totframes && cache->totpoint)
3042                         sprintf(cache->info, "%i points found!", cache->totpoint);
3043                 else
3044                         sprintf(cache->info, "No valid data to read!");
3045                 return;
3046         }
3047
3048         if(cache->flag & PTCACHE_DISK_CACHE) {
3049                 if(pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
3050                 {
3051                         int totpoint = pid->totpoint(pid->calldata, 0);
3052
3053                         if(cache->totpoint > totpoint)
3054                                 sprintf(mem_info, "%i cells + High Resolution cached", totpoint);
3055                         else
3056                                 sprintf(mem_info, "%i cells cached", totpoint);
3057                 }
3058                 else {
3059                         int cfra = cache->startframe;
3060
3061                         for(; cfra<=cache->endframe; cfra++) {
3062                                 if(BKE_ptcache_id_exist(pid, cfra))
3063                                         totframes++;
3064                         }
3065
3066                         sprintf(mem_info, "%i frames on disk", totframes);
3067                 }
3068         }
3069         else {
3070                 PTCacheMem *pm = cache->mem_cache.first;                
3071                 float bytes = 0.0f;
3072                 int i, mb;
3073                 
3074                 for(; pm; pm=pm->next) {
3075                         for(i=0; i<BPHYS_TOT_DATA; i++)
3076                                 bytes += MEM_allocN_len(pm->data[i]);
3077
3078                         for(extra=pm->extradata.first; extra; extra=extra->next) {
3079                                 bytes += MEM_allocN_len(extra->data);
3080                                 bytes += sizeof(PTCacheExtra);
3081                         }
3082
3083                         bytes += sizeof(PTCacheMem);
3084                         
3085                         totframes++;
3086                 }
3087
3088                 mb = (bytes > 1024.0f * 1024.0f);
3089
3090                 sprintf(mem_info, "%i frames in memory (%.1f %s)",
3091                         totframes,
3092                         bytes / (mb ? 1024.0f * 1024.0f : 1024.0f),
3093                         mb ? "Mb" : "kb");
3094         }
3095
3096         if(cache->flag & PTCACHE_OUTDATED) {
3097                 sprintf(cache->info, "%s, cache is outdated!", mem_info);
3098         }
3099         else if(cache->flag & PTCACHE_FRAMES_SKIPPED) {
3100                 sprintf(cache->info, "%s, not exact since frame %i.", mem_info, cache->last_exact);
3101         }
3102         else
3103                 sprintf(cache->info, "%s.", mem_info);
3104 }
3105
3106 void BKE_ptcache_validate(PointCache *cache, int framenr)
3107 {
3108         if(cache) {
3109                 cache->flag |= PTCACHE_SIMULATION_VALID;
3110                 cache->simframe = framenr;
3111         }
3112 }
3113 void BKE_ptcache_invalidate(PointCache *cache)
3114 {
3115         if(cache) {
3116                 cache->flag &= ~PTCACHE_SIMULATION_VALID;
3117                 cache->simframe = 0;
3118                 cache->last_exact = MIN2(cache->startframe, 0);
3119         }
3120 }
3121