summaryrefslogtreecommitdiffstats
path: root/src/gallium/drivers/llvmpipe/lp_setup.c
blob: fcb6e06123d716f430a384a9dded828f30ad5062 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
/**************************************************************************
 *
 * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **************************************************************************/

/**
 * Tiling engine.
 *
 * Builds per-tile display lists and executes them on calls to
 * lp_setup_flush().
 */

#include <limits.h>

#include "pipe/p_defines.h"
#include "util/u_framebuffer.h"
#include "util/u_inlines.h"
#include "util/u_memory.h"
#include "util/u_pack_color.h"
#include "lp_context.h"
#include "lp_memory.h"
#include "lp_scene.h"
#include "lp_scene_queue.h"
#include "lp_texture.h"
#include "lp_debug.h"
#include "lp_fence.h"
#include "lp_query.h"
#include "lp_rast.h"
#include "lp_setup_context.h"
#include "lp_screen.h"
#include "lp_state.h"
#include "state_tracker/sw_winsys.h"

#include "draw/draw_context.h"
#include "draw/draw_vbuf.h"


static void set_scene_state( struct lp_setup_context *, enum setup_state );


struct lp_scene *
lp_setup_get_current_scene(struct lp_setup_context *setup)
{
   if (!setup->scene) {
      set_scene_state( setup, SETUP_EMPTY );
   }
   return setup->scene;
}


/**
 * Check if the size of the current scene has exceeded the limit.
 * If so, flush/render it.
 */
static void
setup_check_scene_size_and_flush(struct lp_setup_context *setup)
{
   if (setup->scene) {
      struct lp_scene *scene = lp_setup_get_current_scene(setup);
      unsigned size = lp_scene_get_size(scene);

      if (size > LP_MAX_SCENE_SIZE) {
         /*printf("LLVMPIPE: scene size = %u, flushing.\n", size);*/
         set_scene_state( setup, SETUP_FLUSHED );
         /*assert(lp_scene_get_size(scene) == 0);*/
      }
   }
}


static void
first_triangle( struct lp_setup_context *setup,
                const float (*v0)[4],
                const float (*v1)[4],
                const float (*v2)[4])
{
   set_scene_state( setup, SETUP_ACTIVE );
   lp_setup_choose_triangle( setup );
   setup->triangle( setup, v0, v1, v2 );
}

static void
first_line( struct lp_setup_context *setup,
	    const float (*v0)[4],
	    const float (*v1)[4])
{
   set_scene_state( setup, SETUP_ACTIVE );
   lp_setup_choose_line( setup );
   setup->line( setup, v0, v1 );
}

static void
first_point( struct lp_setup_context *setup,
	     const float (*v0)[4])
{
   set_scene_state( setup, SETUP_ACTIVE );
   lp_setup_choose_point( setup );
   setup->point( setup, v0 );
}

static void reset_context( struct lp_setup_context *setup )
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   /* Reset derived state */
   setup->constants.stored_size = 0;
   setup->constants.stored_data = NULL;
   setup->fs.stored = NULL;
   setup->dirty = ~0;

   /* no current bin */
   setup->scene = NULL;

   /* Reset some state:
    */
   setup->clear.flags = 0;
   setup->clear.clearzs.clearzs_mask = 0;

   /* Have an explicit "start-binning" call and get rid of this
    * pointer twiddling?
    */
   setup->line = first_line;
   setup->point = first_point;
   setup->triangle = first_triangle;
}


/** Rasterize all scene's bins */
static void
lp_setup_rasterize_scene( struct lp_setup_context *setup )
{
   struct lp_scene *scene = lp_setup_get_current_scene(setup);

   lp_scene_rasterize(scene, setup->rast);

   reset_context( setup );

   LP_DBG(DEBUG_SETUP, "%s done \n", __FUNCTION__);
}



static void
begin_binning( struct lp_setup_context *setup )
{
   struct lp_scene *scene = lp_setup_get_current_scene(setup);
   boolean need_zsload = FALSE;
   if (setup->fb.zsbuf &&
       ((setup->clear.flags & PIPE_CLEAR_DEPTHSTENCIL) != PIPE_CLEAR_DEPTHSTENCIL) &&
        util_format_is_depth_and_stencil(setup->fb.zsbuf->format))
      need_zsload = TRUE;

   LP_DBG(DEBUG_SETUP, "%s color: %s depth: %s\n", __FUNCTION__,
          (setup->clear.flags & PIPE_CLEAR_COLOR) ? "clear": "load",
          need_zsload ? "clear": "load");

   if (setup->fb.nr_cbufs) {
      if (setup->clear.flags & PIPE_CLEAR_COLOR) {
         lp_scene_bin_everywhere( scene, 
				  lp_rast_clear_color, 
				  setup->clear.color );
         scene->has_color_clear = TRUE;
      }
   }

   if (setup->fb.zsbuf) {
      if (setup->clear.flags & PIPE_CLEAR_DEPTHSTENCIL) {
         if (!need_zsload)
            scene->has_depthstencil_clear = TRUE;
         lp_scene_bin_everywhere( scene,
                                  lp_rast_clear_zstencil,
                                  lp_rast_arg_clearzs(&setup->clear.clearzs) );
      }
   }

   LP_DBG(DEBUG_SETUP, "%s done\n", __FUNCTION__);
}


/* This basically bins and then flushes any outstanding full-screen
 * clears.  
 *
 * TODO: fast path for fullscreen clears and no triangles.
 */
static void
execute_clears( struct lp_setup_context *setup )
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   begin_binning( setup );
   lp_setup_rasterize_scene( setup );
}


static void
set_scene_state( struct lp_setup_context *setup,
                 enum setup_state new_state )
{
   unsigned old_state = setup->state;

   if (old_state == new_state)
      return;
       
   LP_DBG(DEBUG_SETUP, "%s old %d new %d\n", __FUNCTION__, old_state, new_state);

   switch (new_state) {
   case SETUP_EMPTY:
      assert(old_state == SETUP_FLUSHED);
      assert(setup->scene == NULL);

      /* wait for a free/empty scene
       */
      setup->scene = lp_scene_dequeue(setup->empty_scenes, TRUE);
      assert(lp_scene_is_empty(setup->scene));
      lp_scene_begin_binning(setup->scene,
                             &setup->fb );
      break;

   case SETUP_CLEARED:
      assert(old_state == SETUP_EMPTY);
      assert(setup->scene != NULL);
      break;

   case SETUP_ACTIVE:
      assert(old_state == SETUP_EMPTY ||
             old_state == SETUP_CLEARED);
      assert(setup->scene != NULL);
      begin_binning( setup );
      break;

   case SETUP_FLUSHED:
      if (old_state == SETUP_CLEARED)
         execute_clears( setup );
      else
         lp_setup_rasterize_scene( setup );
      assert(setup->scene == NULL);
      break;

   default:
      assert(0 && "invalid setup state mode");
   }

   setup->state = new_state;
}


/**
 * \param flags  bitmask of PIPE_FLUSH_x flags
 */
void
lp_setup_flush( struct lp_setup_context *setup,
                unsigned flags )
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   if (setup->scene) {
      struct lp_scene *scene = lp_setup_get_current_scene(setup);
      union lp_rast_cmd_arg dummy = {0};

      if (flags & (PIPE_FLUSH_SWAPBUFFERS |
                   PIPE_FLUSH_FRAME)) {
         /* Store colors in the linear color buffer(s).
          * If we don't do this here, we'll end up converting the tiled
          * data to linear in the texture_unmap() function, which will
          * not be a parallel/threaded operation as here.
          */
         lp_scene_bin_everywhere(scene, lp_rast_store_color, dummy);
      }
   }

   set_scene_state( setup, SETUP_FLUSHED );
}


void
lp_setup_bind_framebuffer( struct lp_setup_context *setup,
                           const struct pipe_framebuffer_state *fb )
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   /* Flush any old scene.
    */
   set_scene_state( setup, SETUP_FLUSHED );

   /*
    * Ensure the old scene is not reused.
    */
   assert(!setup->scene);

   /* Set new state.  This will be picked up later when we next need a
    * scene.
    */
   util_copy_framebuffer_state(&setup->fb, fb);
}


void
lp_setup_clear( struct lp_setup_context *setup,
                const float *color,
                double depth,
                unsigned stencil,
                unsigned flags )
{
   struct lp_scene *scene = lp_setup_get_current_scene(setup);
   unsigned i;
   boolean full_zs_clear = TRUE;
   uint32_t mask = 0;

   LP_DBG(DEBUG_SETUP, "%s state %d\n", __FUNCTION__, setup->state);


   if (flags & PIPE_CLEAR_COLOR) {
      for (i = 0; i < 4; ++i)
         setup->clear.color.clear_color[i] = float_to_ubyte(color[i]);
   }

   if (flags & PIPE_CLEAR_DEPTHSTENCIL) {
      if (setup->fb.zsbuf &&
          ((flags & PIPE_CLEAR_DEPTHSTENCIL) != PIPE_CLEAR_DEPTHSTENCIL) &&
           util_format_is_depth_and_stencil(setup->fb.zsbuf->format))
         full_zs_clear = FALSE;

      if (full_zs_clear) {
         setup->clear.clearzs.clearzs_value =
            util_pack_z_stencil(setup->fb.zsbuf->format,
                                depth,
                                stencil);
         setup->clear.clearzs.clearzs_mask = 0xffffffff;
      }
      else {
         /* hmm */
         uint32_t tmpval;
         if (flags & PIPE_CLEAR_DEPTH) {
            tmpval = util_pack_z(setup->fb.zsbuf->format,
                                 depth);
            switch (setup->fb.zsbuf->format) {
            case PIPE_FORMAT_Z24_UNORM_S8_USCALED:
               mask = 0xffffff;
               break;
            case PIPE_FORMAT_S8_USCALED_Z24_UNORM:
               mask = 0xffffff00;
               break;
            default:
               assert(0);
            }
         }
         else {
            switch (setup->fb.zsbuf->format) {
            case PIPE_FORMAT_Z24_UNORM_S8_USCALED:
               mask = 0xff000000;
               tmpval = stencil << 24;
               break;
            case PIPE_FORMAT_S8_USCALED_Z24_UNORM:
               mask = 0xff;
               tmpval = stencil;
               break;
            default:
               assert(0);
               tmpval = 0;
            }
         }
         setup->clear.clearzs.clearzs_mask |= mask;
         setup->clear.clearzs.clearzs_value =
            (setup->clear.clearzs.clearzs_value & ~mask) | (tmpval & mask);
      }
   }

   if (setup->state == SETUP_ACTIVE) {
      /* Add the clear to existing scene.  In the unusual case where
       * both color and depth-stencil are being cleared when there's
       * already been some rendering, we could discard the currently
       * binned scene and start again, but I don't see that as being
       * a common usage.
       */
      if (flags & PIPE_CLEAR_COLOR) {
         lp_scene_bin_everywhere( scene, 
                                  lp_rast_clear_color,
                                  setup->clear.color );
         scene->has_color_clear = TRUE;
      }

      if (flags & PIPE_CLEAR_DEPTHSTENCIL) {
         if (full_zs_clear)
            scene->has_depthstencil_clear = TRUE;
         else
            setup->clear.clearzs.clearzs_mask = mask;
         lp_scene_bin_everywhere( scene,
                                  lp_rast_clear_zstencil,
                                  lp_rast_arg_clearzs(&setup->clear.clearzs) );


      }

   }
   else {
      /* Put ourselves into the 'pre-clear' state, specifically to try
       * and accumulate multiple clears to color and depth_stencil
       * buffers which the app or state-tracker might issue
       * separately.
       */
      set_scene_state( setup, SETUP_CLEARED );

      setup->clear.flags |= flags;
   }
}


/**
 * Emit a fence.
 */
struct pipe_fence_handle *
lp_setup_fence( struct lp_setup_context *setup )
{
   if (setup->num_threads == 0) {
      return NULL;
   }
   else {
      struct lp_scene *scene = lp_setup_get_current_scene(setup);
      const unsigned rank = lp_scene_get_num_bins( scene ); /* xxx */
      struct lp_fence *fence = lp_fence_create(rank);

      LP_DBG(DEBUG_SETUP, "%s rank %u\n", __FUNCTION__, rank);

      set_scene_state( setup, SETUP_ACTIVE );

      /* insert the fence into all command bins */
      lp_scene_bin_everywhere( scene,
                               lp_rast_fence,
                               lp_rast_arg_fence(fence) );

      return (struct pipe_fence_handle *) fence;
   }
}


void 
lp_setup_set_triangle_state( struct lp_setup_context *setup,
                             unsigned cull_mode,
                             boolean ccw_is_frontface,
                             boolean scissor,
                             boolean gl_rasterization_rules)
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   setup->ccw_is_frontface = ccw_is_frontface;
   setup->cullmode = cull_mode;
   setup->triangle = first_triangle;
   setup->scissor_test = scissor;
   setup->pixel_offset = gl_rasterization_rules ? 0.5f : 0.0f;
}



void
lp_setup_set_fs_inputs( struct lp_setup_context *setup,
                        const struct lp_shader_input *input,
                        unsigned nr )
{
   LP_DBG(DEBUG_SETUP, "%s %p %u\n", __FUNCTION__, (void *) input, nr);

   memcpy( setup->fs.input, input, nr * sizeof input[0] );
   setup->fs.nr_inputs = nr;
}

void
lp_setup_set_fs_variant( struct lp_setup_context *setup,
                         struct lp_fragment_shader_variant *variant)
{
   LP_DBG(DEBUG_SETUP, "%s %p\n", __FUNCTION__,
          variant);
   /* FIXME: reference count */

   setup->fs.current.variant = variant;
   setup->dirty |= LP_SETUP_NEW_FS;
}

void
lp_setup_set_fs_constants(struct lp_setup_context *setup,
                          struct pipe_resource *buffer)
{
   LP_DBG(DEBUG_SETUP, "%s %p\n", __FUNCTION__, (void *) buffer);

   pipe_resource_reference(&setup->constants.current, buffer);

   setup->dirty |= LP_SETUP_NEW_CONSTANTS;
}


void
lp_setup_set_alpha_ref_value( struct lp_setup_context *setup,
                              float alpha_ref_value )
{
   LP_DBG(DEBUG_SETUP, "%s %f\n", __FUNCTION__, alpha_ref_value);

   if(setup->fs.current.jit_context.alpha_ref_value != alpha_ref_value) {
      setup->fs.current.jit_context.alpha_ref_value = alpha_ref_value;
      setup->dirty |= LP_SETUP_NEW_FS;
   }
}

void
lp_setup_set_stencil_ref_values( struct lp_setup_context *setup,
                                 const ubyte refs[2] )
{
   LP_DBG(DEBUG_SETUP, "%s %d %d\n", __FUNCTION__, refs[0], refs[1]);

   if (setup->fs.current.jit_context.stencil_ref_front != refs[0] ||
       setup->fs.current.jit_context.stencil_ref_back != refs[1]) {
      setup->fs.current.jit_context.stencil_ref_front = refs[0];
      setup->fs.current.jit_context.stencil_ref_back = refs[1];
      setup->dirty |= LP_SETUP_NEW_FS;
   }
}

void
lp_setup_set_blend_color( struct lp_setup_context *setup,
                          const struct pipe_blend_color *blend_color )
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   assert(blend_color);

   if(memcmp(&setup->blend_color.current, blend_color, sizeof *blend_color) != 0) {
      memcpy(&setup->blend_color.current, blend_color, sizeof *blend_color);
      setup->dirty |= LP_SETUP_NEW_BLEND_COLOR;
   }
}


void
lp_setup_set_scissor( struct lp_setup_context *setup,
                      const struct pipe_scissor_state *scissor )
{
   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   assert(scissor);

   if (memcmp(&setup->scissor.current, scissor, sizeof(*scissor)) != 0) {
      setup->scissor.current = *scissor; /* struct copy */
      setup->dirty |= LP_SETUP_NEW_SCISSOR;
   }
}


void 
lp_setup_set_flatshade_first( struct lp_setup_context *setup,
                              boolean flatshade_first )
{
   setup->flatshade_first = flatshade_first;
}


void 
lp_setup_set_vertex_info( struct lp_setup_context *setup,
                          struct vertex_info *vertex_info )
{
   /* XXX: just silently holding onto the pointer:
    */
   setup->vertex_info = vertex_info;
}


/**
 * Called during state validation when LP_NEW_SAMPLER_VIEW is set.
 */
void
lp_setup_set_fragment_sampler_views(struct lp_setup_context *setup,
                                    unsigned num,
                                    struct pipe_sampler_view **views)
{
   unsigned i;

   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   assert(num <= PIPE_MAX_SAMPLERS);

   for (i = 0; i < PIPE_MAX_SAMPLERS; i++) {
      struct pipe_sampler_view *view = i < num ? views[i] : NULL;

      if(view) {
         struct pipe_resource *tex = view->texture;
         struct llvmpipe_resource *lp_tex = llvmpipe_resource(tex);
         struct lp_jit_texture *jit_tex;
         jit_tex = &setup->fs.current.jit_context.textures[i];
         jit_tex->width = tex->width0;
         jit_tex->height = tex->height0;
         jit_tex->depth = tex->depth0;
         jit_tex->last_level = tex->last_level;

         /* We're referencing the texture's internal data, so save a
          * reference to it.
          */
         pipe_resource_reference(&setup->fs.current_tex[i], tex);

         if (!lp_tex->dt) {
            /* regular texture - setup array of mipmap level pointers */
            int j;
            for (j = 0; j <= tex->last_level; j++) {
               jit_tex->data[j] =
                  llvmpipe_get_texture_image_all(lp_tex, j, LP_TEX_USAGE_READ,
                                                 LP_TEX_LAYOUT_LINEAR);
               jit_tex->row_stride[j] = lp_tex->row_stride[j];
               jit_tex->img_stride[j] = lp_tex->img_stride[j];

               if (!jit_tex->data[j]) {
                  /* out of memory - use dummy tile memory */
                  jit_tex->data[j] = lp_get_dummy_tile();
                  jit_tex->width = TILE_SIZE;
                  jit_tex->height = TILE_SIZE;
                  jit_tex->depth = 1;
                  jit_tex->last_level = 0;
                  jit_tex->row_stride[j] = 0;
                  jit_tex->img_stride[j] = 0;
               }
            }
         }
         else {
            /* display target texture/surface */
            /*
             * XXX: Where should this be unmapped?
             */
            struct llvmpipe_screen *screen = llvmpipe_screen(tex->screen);
            struct sw_winsys *winsys = screen->winsys;
            jit_tex->data[0] = winsys->displaytarget_map(winsys, lp_tex->dt,
							 PIPE_TRANSFER_READ);
            jit_tex->row_stride[0] = lp_tex->row_stride[0];
            jit_tex->img_stride[0] = lp_tex->img_stride[0];
            assert(jit_tex->data[0]);
         }
      }
   }

   setup->dirty |= LP_SETUP_NEW_FS;
}


/**
 * Called during state validation when LP_NEW_SAMPLER_VIEW is set.
 */
void
lp_setup_set_vertex_sampler_views(struct lp_setup_context *setup,
                                  unsigned num,
                                  struct pipe_sampler_view **views)
{
   unsigned i;
   uint32_t row_stride[DRAW_MAX_TEXTURE_LEVELS];
   uint32_t img_stride[DRAW_MAX_TEXTURE_LEVELS];
   const void *data[DRAW_MAX_TEXTURE_LEVELS];
   struct lp_scene *scene;
   struct llvmpipe_context *lp;

   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   assert(num <= PIPE_MAX_VERTEX_SAMPLERS);

   scene = lp_setup_get_current_scene(setup);
   lp = llvmpipe_context(scene->pipe);

   for (i = 0; i < PIPE_MAX_VERTEX_SAMPLERS; i++) {
      struct pipe_sampler_view *view = i < num ? views[i] : NULL;

      if (view) {
         struct pipe_resource *tex = view->texture;
         struct llvmpipe_resource *lp_tex = llvmpipe_resource(tex);

         /* We're referencing the texture's internal data, so save a
          * reference to it.
          */
         pipe_resource_reference(&setup->vs.current_tex[i], tex);

         if (!lp_tex->dt) {
            /* regular texture - setup array of mipmap level pointers */
            int j;
            for (j = 0; j <= tex->last_level; j++) {
               data[j] =
                  llvmpipe_get_texture_image_all(lp_tex, j, LP_TEX_USAGE_READ,
                                                 LP_TEX_LAYOUT_LINEAR);
               row_stride[j] = lp_tex->row_stride[j];
               img_stride[j] = lp_tex->img_stride[j];
            }
         }
         else {
            /* display target texture/surface */
            /*
             * XXX: Where should this be unmapped?
             */
            struct llvmpipe_screen *screen = llvmpipe_screen(tex->screen);
            struct sw_winsys *winsys = screen->winsys;
            data[0] = winsys->displaytarget_map(winsys, lp_tex->dt,
                                                PIPE_TRANSFER_READ);
            row_stride[0] = lp_tex->row_stride[0];
            img_stride[0] = lp_tex->img_stride[0];
            assert(data[0]);
         }
         draw_set_mapped_texture(lp->draw,
                                 i,
                                 tex->width0, tex->height0, tex->depth0,
                                 tex->last_level,
                                 row_stride, img_stride, data);
      }
   }
}



/**
 * Is the given texture referenced by any scene?
 * Note: we have to check all scenes including any scenes currently
 * being rendered and the current scene being built.
 */
unsigned
lp_setup_is_resource_referenced( const struct lp_setup_context *setup,
                                const struct pipe_resource *texture )
{
   unsigned i;

   /* check the render targets */
   for (i = 0; i < setup->fb.nr_cbufs; i++) {
      if (setup->fb.cbufs[i]->texture == texture)
         return PIPE_REFERENCED_FOR_READ | PIPE_REFERENCED_FOR_WRITE;
   }
   if (setup->fb.zsbuf && setup->fb.zsbuf->texture == texture) {
      return PIPE_REFERENCED_FOR_READ | PIPE_REFERENCED_FOR_WRITE;
   }

   /* check textures referenced by the scene */
   for (i = 0; i < Elements(setup->scenes); i++) {
      if (lp_scene_is_resource_referenced(setup->scenes[i], texture)) {
         return PIPE_REFERENCED_FOR_READ;
      }
   }

   return PIPE_UNREFERENCED;
}


/**
 * Called by vbuf code when we're about to draw something.
 */
void
lp_setup_update_state( struct lp_setup_context *setup )
{
   struct lp_scene *scene;

   LP_DBG(DEBUG_SETUP, "%s\n", __FUNCTION__);

   setup_check_scene_size_and_flush(setup);

   scene = lp_setup_get_current_scene(setup);

   assert(setup->fs.current.variant);

   /* Some of the 'draw' pipeline stages may have changed some driver state.
    * Make sure we've processed those state changes before anything else.
    *
    * XXX this is the only place where llvmpipe_context is used in the
    * setup code.  This may get refactored/changed...
    */
   {
      struct llvmpipe_context *lp = llvmpipe_context(scene->pipe);
      if (lp->dirty) {
         llvmpipe_update_derived(lp);
      }
      assert(lp->dirty == 0);
   }

   if(setup->dirty & LP_SETUP_NEW_BLEND_COLOR) {
      uint8_t *stored;
      unsigned i, j;

      stored = lp_scene_alloc_aligned(scene, 4 * 16, 16);

      if (stored) {
         /* smear each blend color component across 16 ubyte elements */
         for (i = 0; i < 4; ++i) {
            uint8_t c = float_to_ubyte(setup->blend_color.current.color[i]);
            for (j = 0; j < 16; ++j)
               stored[i*16 + j] = c;
         }

         setup->blend_color.stored = stored;

         setup->fs.current.jit_context.blend_color = setup->blend_color.stored;
      }

      setup->dirty |= LP_SETUP_NEW_FS;
   }

   if (setup->dirty & LP_SETUP_NEW_SCISSOR) {
      float *stored;

      stored = lp_scene_alloc_aligned(scene, 4 * sizeof(int32_t), 16);

      if (stored) {
         stored[0] = (float) setup->scissor.current.minx;
         stored[1] = (float) setup->scissor.current.miny;
         stored[2] = (float) setup->scissor.current.maxx;
         stored[3] = (float) setup->scissor.current.maxy;

         setup->scissor.stored = stored;

         setup->fs.current.jit_context.scissor_xmin = stored[0];
         setup->fs.current.jit_context.scissor_ymin = stored[1];
         setup->fs.current.jit_context.scissor_xmax = stored[2];
         setup->fs.current.jit_context.scissor_ymax = stored[3];
      }

      setup->dirty |= LP_SETUP_NEW_FS;
   }

   if(setup->dirty & LP_SETUP_NEW_CONSTANTS) {
      struct pipe_resource *buffer = setup->constants.current;

      if(buffer) {
         unsigned current_size = buffer->width0;
         const void *current_data = llvmpipe_resource_data(buffer);

         /* TODO: copy only the actually used constants? */

         if(setup->constants.stored_size != current_size ||
            !setup->constants.stored_data ||
            memcmp(setup->constants.stored_data,
                   current_data,
                   current_size) != 0) {
            void *stored;

            stored = lp_scene_alloc(scene, current_size);
            if(stored) {
               memcpy(stored,
                      current_data,
                      current_size);
               setup->constants.stored_size = current_size;
               setup->constants.stored_data = stored;
            }
         }
      }
      else {
         setup->constants.stored_size = 0;
         setup->constants.stored_data = NULL;
      }

      setup->fs.current.jit_context.constants = setup->constants.stored_data;
      setup->dirty |= LP_SETUP_NEW_FS;
   }


   if(setup->dirty & LP_SETUP_NEW_FS) {
      if(!setup->fs.stored ||
         memcmp(setup->fs.stored,
                &setup->fs.current,
                sizeof setup->fs.current) != 0) {
         /* The fs state that's been stored in the scene is different from
          * the new, current state.  So allocate a new lp_rast_state object
          * and append it to the bin's setup data buffer.
          */
         uint i;
         struct lp_rast_state *stored =
            (struct lp_rast_state *) lp_scene_alloc(scene, sizeof *stored);
         if(stored) {
            memcpy(stored,
                   &setup->fs.current,
                   sizeof setup->fs.current);
            setup->fs.stored = stored;

            /* put the state-set command into all bins */
            lp_scene_bin_state_command( scene,
					lp_rast_set_state, 
					lp_rast_arg_state(setup->fs.stored) );
         }

         /* The scene now references the textures in the rasterization
          * state record.  Note that now.
          */
         for (i = 0; i < Elements(setup->fs.current_tex); i++) {
            if (setup->fs.current_tex[i])
               lp_scene_add_resource_reference(scene, setup->fs.current_tex[i]);
         }
      }
   }

   setup->dirty = 0;

   assert(setup->fs.stored);
}



/* Only caller is lp_setup_vbuf_destroy()
 */
void 
lp_setup_destroy( struct lp_setup_context *setup )
{
   uint i;

   reset_context( setup );

   util_unreference_framebuffer_state(&setup->fb);

   for (i = 0; i < Elements(setup->vs.current_tex); i++) {
      pipe_resource_reference(&setup->vs.current_tex[i], NULL);
   }
   for (i = 0; i < Elements(setup->fs.current_tex); i++) {
      pipe_resource_reference(&setup->fs.current_tex[i], NULL);
   }

   pipe_resource_reference(&setup->constants.current, NULL);

   /* free the scenes in the 'empty' queue */
   while (1) {
      struct lp_scene *scene = lp_scene_dequeue(setup->empty_scenes, FALSE);
      if (!scene)
         break;
      lp_scene_destroy(scene);
   }

   lp_scene_queue_destroy(setup->empty_scenes);

   lp_rast_destroy( setup->rast );

   FREE( setup );
}


/**
 * Create a new primitive tiling engine.  Plug it into the backend of
 * the draw module.  Currently also creates a rasterizer to use with
 * it.
 */
struct lp_setup_context *
lp_setup_create( struct pipe_context *pipe,
                 struct draw_context *draw )
{
   struct llvmpipe_screen *screen = llvmpipe_screen(pipe->screen);
   struct lp_setup_context *setup = CALLOC_STRUCT(lp_setup_context);
   unsigned i;

   if (!setup)
      return NULL;

   lp_setup_init_vbuf(setup);

   setup->empty_scenes = lp_scene_queue_create();
   if (!setup->empty_scenes)
      goto fail;

   /* XXX: move this to the screen and share between contexts:
    */
   setup->num_threads = screen->num_threads;
   setup->rast = lp_rast_create(screen->num_threads);
   if (!setup->rast) 
      goto fail;

   setup->vbuf = draw_vbuf_stage(draw, &setup->base);
   if (!setup->vbuf)
      goto fail;

   draw_set_rasterize_stage(draw, setup->vbuf);
   draw_set_render(draw, &setup->base);

   /* create some empty scenes */
   for (i = 0; i < MAX_SCENES; i++) {
      setup->scenes[i] = lp_scene_create( pipe, setup->empty_scenes );

      lp_scene_enqueue(setup->empty_scenes, setup->scenes[i]);
   }

   setup->triangle = first_triangle;
   setup->line     = first_line;
   setup->point    = first_point;
   
   setup->dirty = ~0;

   return setup;

fail:
   if (setup->rast)
      lp_rast_destroy( setup->rast );
   
   if (setup->vbuf)
      ;

   if (setup->empty_scenes)
      lp_scene_queue_destroy(setup->empty_scenes);

   FREE(setup);
   return NULL;
}


/**
 * Put a BeginQuery command into all bins.
 */
void
lp_setup_begin_query(struct lp_setup_context *setup,
                     struct llvmpipe_query *pq)
{
   struct lp_scene * scene = lp_setup_get_current_scene(setup);
   union lp_rast_cmd_arg cmd_arg;

   /* init the query to its beginning state */
   pq->done = FALSE;
   pq->tile_count = 0;
   pq->num_tiles = scene->tiles_x * scene->tiles_y;
   assert(pq->num_tiles > 0);

   memset(pq->count, 0, sizeof(pq->count));  /* reset all counters */

   set_scene_state( setup, SETUP_ACTIVE );

   cmd_arg.query_obj = pq;
   lp_scene_bin_everywhere(scene, lp_rast_begin_query, cmd_arg);
   pq->binned = TRUE;
}


/**
 * Put an EndQuery command into all bins.
 */
void
lp_setup_end_query(struct lp_setup_context *setup, struct llvmpipe_query *pq)
{
   struct lp_scene * scene = lp_setup_get_current_scene(setup);
   union lp_rast_cmd_arg cmd_arg;

   set_scene_state( setup, SETUP_ACTIVE );

   cmd_arg.query_obj = pq;
   lp_scene_bin_everywhere(scene, lp_rast_end_query, cmd_arg);
}