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