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